Changeset 73d0c54a


Ignore:
Timestamp:
Apr 21, 2021, 3:39:14 PM (3 years ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
ADT, arm-eh, ast-experimental, enum, forall-pointer-decay, jacob/cs343-translation, master, new-ast-unique-expr, pthread-emulation, qualifiedEnum
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:
2 added
4 deleted
18 edited
2 moved

Legend:

Unmodified
Added
Removed
  • benchmark/readyQ/cycle.cpp

    r665edf40 r73d0c54a  
    33#include <libfibre/fibre.h>
    44
    5 class __attribute__((aligned(128))) bench_sem {
    6         Fibre * volatile ptr = nullptr;
    7 public:
    8         inline bool wait() {
    9                 static Fibre * const ready  = reinterpret_cast<Fibre * const>(1ull);
    10                 for(;;) {
    11                         Fibre * expected = this->ptr;
    12                         if(expected == ready) {
    13                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    14                                         return false;
    15                                 }
    16                         }
    17                         else {
    18                                 /* paranoid */ assert( expected == nullptr );
    19                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    20                                         fibre_park();
    21                                         return true;
    22                                 }
    23                         }
    24 
    25                 }
    26         }
    27 
    28         inline bool post() {
    29                 static Fibre * const ready  = reinterpret_cast<Fibre * const>(1ull);
    30                 for(;;) {
    31                         Fibre * expected = this->ptr;
    32                         if(expected == ready) return false;
    33                         if(expected == nullptr) {
    34                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    35                                         return false;
    36                                 }
    37                         }
    38                         else {
    39                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    40                                         fibre_unpark( expected );
    41                                         return true;
    42                                 }
    43                         }
    44                 }
    45         }
    46 };
    475struct Partner {
    486        unsigned long long count  = 0;
  • benchmark/readyQ/locality.cpp

    r665edf40 r73d0c54a  
    99        uint64_t dmigs = 0;
    1010        uint64_t gmigs = 0;
    11 };
    12 
    13 class __attribute__((aligned(128))) bench_sem {
    14         Fibre * volatile ptr = nullptr;
    15 public:
    16         inline bool wait() {
    17                 static Fibre * const ready  = reinterpret_cast<Fibre * const>(1ull);
    18                 for(;;) {
    19                         Fibre * expected = this->ptr;
    20                         if(expected == ready) {
    21                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    22                                         return false;
    23                                 }
    24                         }
    25                         else {
    26                                 /* paranoid */ assert( expected == nullptr );
    27                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    28                                         fibre_park();
    29                                         return true;
    30                                 }
    31                         }
    32 
    33                 }
    34         }
    35 
    36         inline bool post() {
    37                 static Fibre * const ready  = reinterpret_cast<Fibre * const>(1ull);
    38                 for(;;) {
    39                         Fibre * expected = this->ptr;
    40                         if(expected == ready) return false;
    41                         if(expected == nullptr) {
    42                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    43                                         return false;
    44                                 }
    45                         }
    46                         else {
    47                                 if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    48                                         fibre_unpark( expected );
    49                                         return true;
    50                                 }
    51                         }
    52                 }
    53         }
    5411};
    5512
  • benchmark/readyQ/rq_bench.hfa

    r665edf40 r73d0c54a  
    44#include <stdio.h>
    55#include <stdlib.hfa>
     6#include <stats.hfa>
    67#include <thread.hfa>
    78#include <time.hfa>
     
    6364                (*p){ "Benchmark Processor", this.cl };
    6465        }
     66        #if !defined(__CFA_NO_STATISTICS__)
     67                print_stats_at_exit( this.cl, CFA_STATS_READY_Q );
     68        #endif
    6569}
    6670
  • benchmark/readyQ/rq_bench.hpp

    r665edf40 r73d0c54a  
    66#include <time.h>                                                                               // timespec
    77#include <sys/time.h>                                                                   // timeval
     8
     9typedef __uint128_t __lehmer64_state_t;
     10static inline uint64_t __lehmer64( __lehmer64_state_t & state ) {
     11        state *= 0xda942042e4dd58b5;
     12        return state >> 64;
     13}
    814
    915enum { TIMEGRAN = 1000000000LL };                                       // nanosecond granularity, except for timeval
     
    7581}
    7682
     83class Fibre;
     84int fibre_park();
     85int fibre_unpark( Fibre * );
     86Fibre * fibre_self();
     87
     88class __attribute__((aligned(128))) bench_sem {
     89        Fibre * volatile ptr = nullptr;
     90public:
     91        inline bool wait() {
     92                static Fibre * const ready  = reinterpret_cast<Fibre *>(1ull);
     93                for(;;) {
     94                        Fibre * expected = this->ptr;
     95                        if(expected == ready) {
     96                                if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     97                                        return false;
     98                                }
     99                        }
     100                        else {
     101                                /* paranoid */ assert( expected == nullptr );
     102                                if(__atomic_compare_exchange_n(&this->ptr, &expected, fibre_self(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     103                                        fibre_park();
     104                                        return true;
     105                                }
     106                        }
     107
     108                }
     109        }
     110
     111        inline bool post() {
     112                static Fibre * const ready  = reinterpret_cast<Fibre *>(1ull);
     113                for(;;) {
     114                        Fibre * expected = this->ptr;
     115                        if(expected == ready) return false;
     116                        if(expected == nullptr) {
     117                                if(__atomic_compare_exchange_n(&this->ptr, &expected, ready, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     118                                        return false;
     119                                }
     120                        }
     121                        else {
     122                                if(__atomic_compare_exchange_n(&this->ptr, &expected, nullptr, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     123                                        fibre_unpark( expected );
     124                                        return true;
     125                                }
     126                        }
     127                }
     128        }
     129};
     130
    77131// ==========================================================================================
    78132#include <cstdlib>
     
    188242                this->help       = help;
    189243                this->variable   = reinterpret_cast<void*>(&variable);
    190                 this->parse_fun  = reinterpret_cast<bool (*)(const char *, void * )>(static_cast<bool (*)(const char *, T & )>(parse));
     244                #pragma GCC diagnostic push
     245                #pragma GCC diagnostic ignored "-Wcast-function-type"
     246                                this->parse_fun  = reinterpret_cast<bool (*)(const char *, void * )>(static_cast<bool (*)(const char *, T & )>(parse));
     247                #pragma GCC diagnostic pop
    191248        }
    192249
     
    197254                this->help       = help;
    198255                this->variable   = reinterpret_cast<void*>(&variable);
    199                 this->parse_fun  = reinterpret_cast<bool (*)(const char *, void * )>(parse);
     256                #pragma GCC diagnostic push
     257                #pragma GCC diagnostic ignored "-Wcast-function-type"
     258                        this->parse_fun  = reinterpret_cast<bool (*)(const char *, void * )>(parse);
     259                #pragma GCC diagnostic pop
    200260        }
    201261};
  • doc/theses/andrew_beach_MMath/Makefile

    r665edf40 r73d0c54a  
    11### Makefile for Andrew Beach's Masters Thesis
    22
    3 DOC = uw-ethesis.pdf
    4 BASE = ${DOC:%.pdf=%} # remove suffix
    5 # directory for latex clutter files
    6 BUILD = build
    7 TEXSRC = $(wildcard *.tex)
    8 FIGSRC = $(wildcard *.fig)
    9 BIBSRC = $(wildcard *.bib)
    10 STYSRC = $(wildcard *.sty)
    11 CLSSRC = $(wildcard *.cls)
    12 TEXLIB = .:../../LaTeXmacros:${BUILD}: # common latex macros
    13 BIBLIB = .:../../bibliography # common citation repository
     3DOC=uw-ethesis.pdf
     4BUILD=out
     5TEXSRC=$(wildcard *.tex)
     6FIGSRC=$(wildcard *.fig)
     7BIBSRC=$(wildcard *.bib)
     8STYSRC=$(wildcard *.sty)
     9CLSSRC=$(wildcard *.cls)
     10TEXLIB= .:../../LaTeXmacros:${BUILD}:
     11BIBLIB= .:../../bibliography
    1412
    15 MAKEFLAGS = --no-print-directory # --silent
    16 VPATH = ${BUILD}
     13# Since tex programs like to add their own file extensions:
     14BASE= ${DOC:%.pdf=%}
     15
     16RAWSRC=${TEXSRC} ${BIBSRC} ${STYSRC} ${CLSSRC}
     17FIGTEX=${FIGSRC:%.fig=${BUILD}/%.tex}
    1718
    1819### Special Rules:
    1920
    2021.PHONY: all clean deepclean
    21 .PRECIOUS: %.dvi %.ps # do not delete intermediate files
    2222
    2323### Commands:
    24 LATEX = TEXINPUTS=${TEXLIB} && export TEXINPUTS && latex -halt-on-error -output-directory=${BUILD}
    25 BIBTEX = BIBINPUTS=${BIBLIB} bibtex
    26 GLOSSARY = INDEXSTYLE=${BUILD} makeglossaries-lite
     24LATEX=TEXINPUTS=${TEXLIB} latex -halt-on-error -output-directory=${BUILD}
     25BIBTEX=BIBINPUTS=${BIBLIB} bibtex
     26GLOSSARY=INDEXSTYLE=${BUILD} makeglossaries-lite
    2727
    28 ### Rules and Recipes:
     28### Rules and Recipies:
    2929
    3030all: ${DOC}
    3131
    32 ${BUILD}/%.dvi: ${TEXSRC} ${FIGSRC:.fig=.tex} ${BIBSRC} ${STYSRC} ${CLSSRC} Makefile | ${BUILD}
     32# The main rule, it does all the tex/latex processing.
     33${BUILD}/${BASE}.dvi: ${RAWSRC} ${FIGTEX} Makefile | ${BUILD}
    3334        ${LATEX} ${BASE}
    3435        ${BIBTEX} ${BUILD}/${BASE}
     
    3738        ${LATEX} ${BASE}
    3839
     40# Convert xfig output to tex. (Generates \special declarations.)
     41${FIGTEX}: ${BUILD}/%.tex: %.fig | ${BUILD}
     42        fig2dev -L eepic $< > $@
     43
     44# Step through dvi & postscript to handle xfig specials.
     45%.pdf : ${BUILD}/%.dvi
     46        dvipdf $^ $@
     47
    3948${BUILD}:
    4049        mkdir $@
    4150
    42 %.pdf : ${BUILD}/%.ps | ${BUILD}
    43         ps2pdf $<
    44 
    45 %.ps : %.dvi | ${BUILD}
    46         dvips $< -o $@
    47 
    48 %.tex : %.fig | ${BUILD}
    49         fig2dev -L eepic $< > ${BUILD}/$@
    50 
    51 %.ps : %.fig | ${BUILD}
    52         fig2dev -L ps $< > ${BUILD}/$@
    53 
    54 %.pstex : %.fig | ${BUILD}
    55         fig2dev -L pstex $< > ${BUILD}/$@
    56         fig2dev -L pstex_t -p ${BUILD}/$@ $< > ${BUILD}/$@_t
    57 
    5851clean:
    59         @rm -frv ${BUILD} *.fig.bak
     52        -@rm -rv ${BUILD}
    6053
    6154deepclean: clean
    62         -@rm -fv ${DOC}
     55        -@rm -v ${DOC}
  • doc/theses/andrew_beach_MMath/features.tex

    r665edf40 r73d0c54a  
    33This chapter covers the design and user interface of the \CFA
    44exception-handling mechanism (EHM). % or exception system.
    5 While an EHM is free to add many features,
    6 the following overview covers the basic features that all EHMs use, but it is not an
    7 exhaustive list of everything an EHM can do.
     5
     6We will begin with an overview of EHMs in general. It is not a strict
     7definition of all EHMs nor an exaustive list of all possible features.
     8However it does cover the most common structure and features found in them.
    89
    910% We should cover what is an exception handling mechanism and what is an
     
    1415These terms are sometimes also known as throw and catch but this work uses
    1516throw/catch as a particular kind of raise/handle.
    16 These are the two parts a programmer writes and so
    17 are the only two pieces of the EHM that have language syntax.
     17These are the two parts that the user will write themselves and may
     18be the only two pieces of the EHM that have any syntax in the language.
    1819
    1920\subparagraph{Raise}
    20 The raise is the starting point for exception handling and usually how \PAB{This sentence is cut off.}
    21 Some well known examples include the @throw@ statement of \Cpp and Java and
    22 the \lstinline[language=Python]{raise} statement from Python.
    23 
    24 For this overview, a raise starts the handling of an
    25 exception, which is called \newterm{raising} an exception. This simple description is sufficient
    26 for the overview.
     21The raise is the starting point for exception handling. It marks the beginning
     22of exception handling by \newterm{raising} an excepion, which passes it to
     23the EHM.
     24
     25Some well known examples include the @throw@ statements of \Cpp and Java and
     26the \codePy{raise} statement from Python. In real systems a raise may preform
     27some other work (such as memory management) but for the purposes of this
     28overview that can be ignored.
    2729
    2830\subparagraph{Handle}
    29 The purpose of raising an exception is to run user code to address (handle) the
    30 issue found at the raise point.
    31 The @try@ statement of \Cpp illustrates a common approach for specifying multiple handlers.
    32 A handler has three common features: the scope in which it applies, an
    33 exception label that describes what exceptions it can handle, and code to run
    34 that deals with the raised issue.
    35 Each handler can handle exceptions raised in the region matching its
    36 exception label. For multiple matches, different EHMs have different rules for matching an exception to a handler label,
    37 such as ``best match" or ``first found".
     31The purpose of most exception operations is to run some user code to handle
     32that exception. This code is given, with some other information, in a handler.
     33
     34A handler has three common features: the previously mentioned user code, a
     35region of code they cover and an exception label/condition that matches
     36certain exceptions.
     37Only raises inside the covered region and raising exceptions that match the
     38label can be handled by a given handler.
     39Different EHMs will have different rules to pick a handler
     40if multipe handlers could be used such as ``best match" or ``first found".
     41
     42The @try@ statements of \Cpp, Java and Python are common examples. All three
     43also show another common feature of handlers, they are grouped by the covered
     44region.
    3845
    3946\paragraph{Propagation}
    40 After an exception is raised, comes the most complex step for the
    41 EHM: finding and setting up the handler. This propagation of exception from raise to handler can be broken up into three
    42 different tasks: searching, matching, and
    43 installing the handler so it can execute.
     47After an exception is raised comes what is usually the biggest step for the
     48EHM: finding and setting up the handler. The propogation from raise to
     49handler can be broken up into three different tasks: searching for a handler,
     50matching against the handler and installing the handler.
    4451
    4552\subparagraph{Searching}
    46 The EHM searches for possible handlers that can be used to handle
    47 the exception. Searching is usually independent of the exception that is
    48 thrown and instead depends on the call stack: current function, its caller
    49 and repeating down the stack.
     53The EHM begins by searching for handlers that might be used to handle
     54the exception. Searching is usually independent of the exception that was
     55thrown as it looks for handlers that have the raise site in their covered
     56region.
     57This includes handlers in the current function, as well as any in callers
     58on the stack that have the function call in their covered region.
    5059
    5160\subparagraph{Matching}
    52 For each handler found, it compares the raised exception with the handler label to see which one is the
    53 best match, and hence, which one should be used to handle the exception.
    54 In languages where the best match is the first match, these two steps are often
    55 intertwined, \ie a match check is performed immediately after the search finds
     61Each handler found has to be matched with the raised exception. The exception
     62label defines a condition that be use used with exception and decides if
     63there is a match or not.
     64
     65In languages where the first match is used this step is intertwined with
     66searching, a match check is preformed immediately after the search finds
    5667a possible handler.
    5768
    5869\subparagraph{Installing}
    59 After a handler is chosen, it must be made ready to run.
    60 This step varies widely to fit with the rest of the
    61 design of the EHM. The installation step might be trivial or it can be
     70After a handler is chosen it must be made ready to run.
     71The implementation can vary widely to fit with the rest of the
     72design of the EHM. The installation step might be trivial or it could be
    6273the most expensive step in handling an exception. The latter tends to be the
    6374case when stack unwinding is involved.
    64 An alternate action occurs if no appropriate handler is found, then some implicit action
    65 is performed. This step is only required with unchecked
    66 exceptions as checked exceptions (Java) promise a handler is always found. The implicit action
    67 also installs a handler but it is a default handle that may be
    68 installed differently.
     75
     76If a matching handler is not guarantied to be found the EHM will need a
     77different course of action here in the cases where no handler matches.
     78This is only required with unchecked exceptions as checked exceptions
     79(such as in Java) can make than guaranty.
     80This different action can also be installing a handler but it is usually an
     81implicat and much more general one.
    6982
    7083\subparagraph{Hierarchy}
    71 Some EHM (\CFA, Java) organize exceptions in a hierarchical structure.
    72 This strategy is borrowed from object-orientated languages where the
     84A common way to organize exceptions is in a hierarchical structure.
     85This is especially true in object-orientated languages where the
    7386exception hierarchy is a natural extension of the object hierarchy.
    7487
    7588Consider the following hierarchy of exceptions:
    7689\begin{center}
    77 \input{exceptionHierarchy}
     90\input{exception-hierarchy}
    7891\end{center}
     92
    7993A handler labelled with any given exception can handle exceptions of that
    8094type or any child type of that exception. The root of the exception hierarchy
    81 (here \lstinline[language=C++]{exception}) acts as a catch-all, leaf types catch single types
     95(here \codeC{exception}) acts as a catch-all, leaf types catch single types
    8296and the exceptions in the middle can be used to catch different groups of
    8397related exceptions.
    8498
    8599This system has some notable advantages, such as multiple levels of grouping,
    86 the ability for libraries to add new exception types, and the isolation
    87 between different sub-hierarchies. This capability had to be adapted for \CFA, which is a
    88 non-object-orientated language.
     100the ability for libraries to add new exception types and the isolation
     101between different sub-hierarchies.
     102This design is used in \CFA even though it is not a object-orientated
     103language using different tools to create the hierarchy.
    89104
    90105% Could I cite the rational for the Python IO exception rework?
    91106
    92107\paragraph{Completion}
    93 After the handler has returned, the entire exception operation has to complete
    94 and continue executing somewhere. This step is usually simple,
     108After the handler has finished the entire exception operation has to complete
     109and continue executing somewhere else. This step is usually simple,
    95110both logically and in its implementation, as the installation of the handler
    96 usually does the preparation.
    97 The EHM can return control to different places,
    98 where the most common are after the handler definition or after the raise.
     111is usually set up to do most of the work.
     112
     113The EHM can return control to many different places,
     114the most common are after the handler definition and after the raise.
    99115
    100116\paragraph{Communication}
    101 For effective exception handling, additional information is usually passed from the raise,
    102 where this basic model only communicates the exception's identity. A common
    103 methods for communication is putting fields into an exception and
    104 allowing a handler to access these fields via an exception instance in the handler's scope.
     117For effective exception handling, additional information is usually passed
     118from the raise to the handler.
     119So far only communication of the exceptions' identity has been covered.
     120A common method is putting fields into the exception instance and giving the
     121handler access to them.
    105122
    106123\section{Virtuals}
    107 Virtual types and casts are not part of an EHM nor are they
    108 required for an EHM. But as pointed out, an object-oriented-style hierarchy is an
    109 excellent way of organizing exceptions. Hence, a minimal virtual system has been added
    110 to \CFA to support hierarchical exceptions.
     124Virtual types and casts are not part of \CFA's EHM nor are they required for
     125any EHM. But \CFA uses a hierarchial system of exceptions and this feature
     126is leveraged to create that.
     127
     128% Maybe talk about why the virtual system is so minimal.
     129% Created for but not a part of the exception system.
    111130
    112131The virtual system supports multiple ``trees" of types. Each tree is
    113132a simple hierarchy with a single root type. Each type in a tree has exactly
    114 one parent -- except for the root type with zero parents -- and any
     133one parent -- except for the root type which has zero parents -- and any
    115134number of children.
    116135Any type that belongs to any of these trees is called a virtual type.
     
    118137% A type's ancestors are its parent and its parent's ancestors.
    119138% The root type has no ancestors.
    120 % A type's descendents are its children and its children's descendents.
    121 
    122 Every virtual type has a list of virtual members. Children inherit
    123 their parent's virtual members but may add new members to it.
    124 It is important to note that these are virtual members, not virtual methods of an object type.
    125 However, as \CFA has function pointers, they can be used to mimic virtual
    126 methods.
     139% A type's decendents are its children and its children's decendents.
     140
     141Every virtual type also has a list of virtual members. Children inherit
     142their parent's list of virtual members but may add new members to it.
     143It is important to note that these are virtual members, not virtual methods
     144of object-orientated programming, and can be of any type.
     145However, since \CFA has function pointers and they are allowed, virtual
     146members can be used to mimic virtual methods.
    127147
    128148Each virtual type has a unique id.
    129 The unique id for the virtual type and all its virtual members are combined
    130 into a virtual-table type. Each virtual type has a pointer to a virtual table
     149This unique id and all the virtual members are combined
     150into a virtual table type. Each virtual type has a pointer to a virtual table
    131151as a hidden field.
    132152
    133 Up to this point, a virtual system is similar to ones found in object-oriented
    134 languages but this is where \CFA diverges. Objects encapsulate a
     153Up until this point the virtual system is similar to ones found in
     154object-orientated languages but this where \CFA diverges. Objects encapsulate a
    135155single set of behaviours in each type, universally across the entire program,
    136 and indeed all programs that use that type definition. In this sense, the
     156and indeed all programs that use that type definition. In this sense the
    137157types are ``closed" and cannot be altered.
    138 However, \CFA types do not encapsulate any behaviour. Instead, traits are used and
    139 types can satisfy a trait, stop satisfying a trait, or satisfy the same
    140 trait in a different way depending on the lexical context. In this sense, the types are
    141 ``open" as their behaviour can change in different scopes. This capability means it is impossible to pick
    142 a single set of functions that represent the type's virtual members.
    143 
    144 Hence, \CFA does not have a single virtual table for a type. A user can define different virtual tables,
    145 which are filled in at their declaration and given a name.
    146 That name is used as the virtual table, even if it is defined locally
    147 inside a function, although lifetime issues must be considered.
    148 Specifically, an object of a virtual type is ``bound" to a virtual table instance, which
     158
     159In \CFA types do not encapsulate any behaviour. Traits are local and
     160types can begin to statify a trait, stop satifying a trait or satify the same
     161trait in a different way at any lexical location in the program.
     162In this sense they are ``open" as they can change at any time. This means it
     163is implossible to pick a single set of functions that repersent the type's
     164implementation across the program.
     165
     166\CFA side-steps this issue by not having a single virtual table for each
     167type. A user can define virtual tables which are filled in at their
     168declaration and given a name. Anywhere that name is visible, even if it was
     169defined locally inside a function (although that means it will not have a
     170static lifetime), it can be used.
     171Specifically, a virtual type is ``bound" to a virtual table which
    149172sets the virtual members for that object. The virtual members can be accessed
    150173through the object.
     
    160183\Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be
    161184a pointer to a virtual type.
    162 The cast dynamically checks if the @EXPRESSION@ type is the same or a subtype
     185The cast dynamically checks if the @EXPRESSION@ type is the same or a sub-type
    163186of @TYPE@, and if true, returns a pointer to the
    164187@EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
     
    178201\end{cfa}
    179202The trait is defined over two types, the exception type and the virtual table
    180 type. These type should have a one-to-one relationship: each exception type has only one virtual
     203type. This should be one-to-one: each exception type has only one virtual
    181204table type and vice versa. The only assertion in the trait is
    182205@get_exception_vtable@, which takes a pointer of the exception type and
    183 returns a reference to the virtual-table type-instance.
    184 
     206returns a reference to the virtual table type instance.
     207
     208% TODO: This section, and all references to get_exception_vtable, are
     209% out-of-data. Perhaps wait until the update is finished before rewriting it.
    185210The function @get_exception_vtable@ is actually a constant function.
    186 Regardless of the value passed in (including the null pointer) it
    187 returns a reference to the virtual-table instance for that type.
    188 The reason it is a function instead of a constant is to make type
    189 annotations easier to write using the exception type rather than the
    190 virtual-table type, which usually has a mangled name because it is an internal component of the EHM.
     211Regardless of the value passed in (including the null pointer) it should
     212return a reference to the virtual table instance for that type.
     213The reason it is a function instead of a constant is that it make type
     214annotations easier to write as you can use the exception type instead of the
     215virtual table type; which usually has a mangled name.
    191216% Also \CFA's trait system handles functions better than constants and doing
    192217% it this way reduce the amount of boiler plate we need.
     
    194219% I did have a note about how it is the programmer's responsibility to make
    195220% sure the function is implemented correctly. But this is true of every
    196 % similar system I know of (except Ada's I guess) so I took it out.
    197 
    198 There are two more exception traits defined as follows:
     221% similar system I know of (except Agda's I guess) so I took it out.
     222
     223There are two more traits for exceptions defined as follows:
    199224\begin{cfa}
    200225trait is_termination_exception(
     
    208233};
    209234\end{cfa}
    210 These traits ensure a given type and virtual type are an
    211 exception type and defines one of the two default handlers. The default handlers
    212 are used in the main exception-handling operations and discussed in detail in \VRef{s:ExceptionHandling}.
    213 
    214 However, all three of these traits are tricky to use directly.
     235Both traits ensure a pair of types are an exception type and its virtual table
     236and defines one of the two default handlers. The default handlers are used
     237as fallbacks and are discussed in detail in \VRef{s:ExceptionHandling}.
     238
     239However, all three of these traits can be tricky to use directly.
    215240While there is a bit of repetition required,
    216 the largest issue is that the virtual-table type is mangled and not in a user
    217 facing way. So three macros are provided to wrap these traits
    218 to simplify referring to the names:
     241the largest issue is that the virtual table type is mangled and not in a user
     242facing way. So these three macros are provided to wrap these traits to
     243simplify referring to the names:
    219244@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
    220245
    221 These macros take one or two arguments. The first argument is the name of the
    222 exception type. The macro passes the unmangled and mangled form to the trait.
     246All three take one or two arguments. The first argument is the name of the
     247exception type. The macro passes its unmangled and mangled form to the trait.
    223248The second (optional) argument is a parenthesized list of polymorphic
    224249arguments. This argument is only used with polymorphic exceptions and the
    225 list is passed to both types.
    226 In the current set-up, the base name and the polymorphic arguments have to
    227 match so these macros can be used without losing flexibility.
     250list is be passed to both types.
     251In the current set-up, the two types always have the same polymorphic
     252arguments so these macros can be used without losing flexibility.
    228253
    229254For example consider a function that is polymorphic over types that have a
    230255defined arithmetic exception:
    231256\begin{cfa}
    232 forall(Num | @IS_EXCEPTION(Arithmetic, Num)@)
     257forall(Num | IS_EXCEPTION(Arithmetic, (Num)))
    233258void some_math_function(Num & left, Num & right);
    234259\end{cfa}
    235 where the function may raise exception @Arithmetic@ or any of its decedents.
    236260
    237261\section{Exception Handling}
    238262\label{s:ExceptionHandling}
    239263\CFA provides two kinds of exception handling: termination and resumption.
    240 These twin mechanisms are the core of the \CFA EHM and
    241 multiple features are provided to support them.
    242 This section covers the general patterns shared by the two kinds of exceptions and
    243 then covers the individual detail operations.
    244 
    245 Both mechanisms follow the same set of steps to do their operations. Both
    246 start with the user performing an exception raise.
    247 Then there is the handler search. If one is found, than the exception
    248 is caught and the handler is run. When the handler returns, control returns to an
    249 location appropriate for each kind of exception.
    250 
    251 \begin{sloppypar}
    252 If the search fails, an appropriate default handler, @defaultTermiationHandler@
    253 or @defaultResumptionHandler@, is run and  control returns to the
    254 appropriate location.
    255 \end{sloppypar}
     264These twin operations are the core of \CFA's exception handling mechanism.
     265This section will cover the general patterns shared by the two operations and
     266then go on to cover the details each individual operation.
     267
     268Both operations follow the same set of steps.
     269Both start with the user preforming a raise on an exception.
     270Then the exception propogates up the stack.
     271If a handler is found the exception is caught and the handler is run.
     272After that control returns to normal execution.
     273If the search fails a default handler is run and then control
     274returns to normal execution after the raise.
     275
     276This general description covers what the two kinds have in common.
     277Differences include how propogation is preformed, where exception continues
     278after an exception is caught and handled and which default handler is run.
    256279
    257280\subsection{Termination}
    258281\label{s:Termination}
    259 Termination handling is familiar and used in most programming
     282Termination handling is the familiar kind and used in most programming
    260283languages with exception handling.
    261 It is a dynamic, non-local goto. The raise starts searching, and if matched and handled, the stack is
    262 unwound and control (usually) continues in the function on
    263 the call stack containing the handler. Terminate is commonly used for an error where recovery
    264 is impossible in the function performing the raise.
     284It is dynamic, non-local goto. If the raised exception is matched and
     285handled the stack is unwound and control will (usually) continue the function
     286on the call stack that defined the handler.
     287Termination is commonly used when an error has occurred and recovery is
     288impossible locally.
    265289
    266290% (usually) Control can continue in the current function but then a different
     
    272296\end{cfa}
    273297The expression must return a reference to a termination exception, where the
    274 termination exception is any type that satisfies trait
    275 @is_termination_exception@ at the call site.  Through \CFA's trait system, the
    276 trait functions are implicitly passed into the hidden throw code and available
    277 to the exception system while handling the exception. A new
    278 @defaultTerminationHandler@ can be defined in any scope to change the throw's
    279 unhandled behaviour (see below).
    280 
    281 The throw must copy the provided exception into managed memory because the stack is unwounded.
    282 The lifetime of the exception copy is managed by the exception runtime.
    283 It is the user's responsibility to ensure the original exception is cleaned up, where allocating it on the unwound stack is sufficient.
    284 
    285 The exception search walks the stack matching with the copied exception.
     298termination exception is any type that satisfies the trait
     299@is_termination_exception@ at the call site.
     300Through \CFA's trait system the trait functions are implicity passed into the
     301throw code and the EHM.
     302A new @defaultTerminationHandler@ can be defined in any scope to
     303change the throw's behavior (see below).
     304
     305The throw will copy the provided exception into managed memory to ensure
     306the exception is not destroyed if the stack is unwound.
     307It is the user's responsibility to ensure the original exception is cleaned
     308up wheither the stack is unwound or not. Allocating it on the stack is
     309usually sufficient.
     310
     311Then propogation starts with the search. \CFA uses a ``first match" rule so
     312matching is preformed with the copied exception as the search continues.
    286313It starts from the throwing function and proceeds to the base of the stack,
    287314from callee to caller.
    288 At each stack frame, a check is made for termination handlers defined by the
     315At each stack frame, a check is made for resumption handlers defined by the
    289316@catch@ clauses of a @try@ statement.
    290317\begin{cfa}
    291318try {
    292319        GUARDED_BLOCK
    293 } catch (EXCEPTION_TYPE$\(_1\)$ [* NAME$\(_1\)$]) {
     320} catch (EXCEPTION_TYPE$\(_1\)$ * [NAME$\(_1\)$]) {
    294321        HANDLER_BLOCK$\(_1\)$
    295 } catch (EXCEPTION_TYPE$\(_2\)$ [* NAME$\(_2\)$]) {
     322} catch (EXCEPTION_TYPE$\(_2\)$ * [NAME$\(_2\)$]) {
    296323        HANDLER_BLOCK$\(_2\)$
    297324}
    298325\end{cfa}
    299 When viewed on its own, a @try@ statement with @catch@ clauses simply executes the statements in
    300 the @GUARDED_BLOCK@, and when those are finished, the try statement finishes.
    301 
    302 However, while the guarded statements are being executed, including any invoked
    303 functions, a termination exception may be thrown. If that exception is not handled by a try
    304 statement further up the stack, the handlers following the try block are now
    305 searched for a matching termination exception-type from top to bottom.
    306 
    307 Exception matching checks each @catch@ clasue from top to bottom, if the representation of the thrown exception-type is
    308 the same or a descendant type of the exception types in the @catch@ clauses. If
    309 it is the same or a descendant of @EXCEPTION_TYPE@$_i$, then the optional @NAME@$_i$ is
     326When viewed on its own, a try statement will simply execute the statements
     327in @GUARDED_BLOCK@ and when those are finished the try statement finishes.
     328
     329However, while the guarded statements are being executed, including any
     330invoked functions, all the handlers in the statement are now on the search
     331path. If a termination exception is thrown and not handled further up the
     332stack they will be matched against the exception.
     333
     334Exception matching checks the handler in each catch clause in the order
     335they appear, top to bottom. If the representation of the thrown exception type
     336is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$
     337(if provided) is
    310338bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$
    311339are executed. If control reaches the end of the handler, the exception is
    312 freed and control continues after the @try@ statement.
    313 
    314 If no termination handler is found during the search, the default termination
    315 handler visible at the raise is called.  Through \CFA's trait-system the best
    316 default-handler match at the throw sight is used.  This function is
    317 passed the copied exception given to the raise. After the default handler is
    318 run, control continues after the @throw@ statement.
    319 
    320 There is a global @defaultTerminationHandler@ function that that is polymorphic
    321 over all exception types allowing new default handlers to be defined for
    322 different exception types and so different exception types can have different
    323 default handlers.  The global default termination-handler performs a
    324 cancellation \see{\VRef{s:Cancellation}} on the current stack with the copied
    325 exception.
     340freed and control continues after the try statement.
     341
     342If no termination handler is found during the search then the default handler
     343(@defaultTerminationHandler@) is run.
     344Through \CFA's trait system the best match at the throw sight will be used.
     345This function is run and is passed the copied exception. After the default
     346handler is run control continues after the throw statement.
     347
     348There is a global @defaultTerminationHandler@ that is polymorphic over all
     349exception types. Since it is so general a more specific handler can be
     350defined and will be used for those types, effectively overriding the handler
     351for particular exception type.
     352The global default termination handler performs a cancellation
     353\see{\VRef{s:Cancellation}} on the current stack with the copied exception.
    326354
    327355\subsection{Resumption}
    328356\label{s:Resumption}
    329 Resumption exception-handling is a less common counterpart to termination but is
    330 just as old~\cite{Goodenough75} and is simpler to understand.
    331 It is a dynamic, non-local function call (like Lisp). If the throw is successful, a
    332 closure is taken from up the stack and executed, after which the throwing
    333 function continues executing.
    334 Resumption is used when an error occurred, and if the error is repaired,
     357
     358Resumption exception handling is less common than termination but is
     359just as old~\cite{Goodenough75} and is simpler in many ways.
     360It is a dynamic, non-local function call. If the raised exception is
     361matched a closure will be taken from up the stack and executed,
     362after which the raising function will continue executing.
     363These are most often used when an error occurred and if the error is repaired
    335364then the function can continue.
    336365
    337 An alternative approach is explicitly passing fixup functions with local
    338 closures up the stack to be called when an error occurs. However, fixup
    339 functions significantly expand the parameters list of functions, even when the
    340 fixup function is not used by a function but must be passed to other called
    341 functions.
    342 
    343366A resumption raise is started with the @throwResume@ statement:
    344367\begin{cfa}
    345368throwResume EXPRESSION;
    346369\end{cfa}
    347 Like termination, the expression must return a reference to a resumption
    348 exception, where the resumption exception is any type that satisfies the trait
    349 @is_termination_exception@ at the call site.
    350 The assertions for this trait are available to
     370It works much the same way as the termination throw.
     371The expression must return a reference to a resumption exception,
     372where the resumption exception is any type that satisfies the trait
     373@is_resumption_exception@ at the call site.
     374The assertions from this trait are available to
    351375the exception system while handling the exception.
    352376
    353 At runtime, no exception copy is made, as the stack is not unwound. Hence, the exception and
    354 any values on the stack remain in scope while the resumption is handled.
    355 
    356 The exception searches walks the stack matching with the provided exception.
    357 It starts from the resuming function and proceeds to the base of the stack,
    358 from callee to caller.
     377At run-time, no exception copy is made.
     378As the stack is not unwound the exception and
     379any values on the stack will remain in scope while the resumption is handled.
     380
     381The EHM then begins propogation. The search starts from the raise in the
     382resuming function and proceeds to the base of the stack, from callee to caller.
    359383At each stack frame, a check is made for resumption handlers defined by the
    360384@catchResume@ clauses of a @try@ statement.
     
    362386try {
    363387        GUARDED_BLOCK
    364 } catchResume (EXCEPTION_TYPE$\(_1\)$ [* NAME$\(_1\)$]) {
     388} catchResume (EXCEPTION_TYPE$\(_1\)$ * [NAME$\(_1\)$]) {
    365389        HANDLER_BLOCK$\(_1\)$
    366 } catchResume (EXCEPTION_TYPE$\(_2\)$ [* NAME$\(_2\)$]) {
     390} catchResume (EXCEPTION_TYPE$\(_2\)$ * [NAME$\(_2\)$]) {
    367391        HANDLER_BLOCK$\(_2\)$
    368392}
    369393\end{cfa}
    370 Termination and resumption handlers may be intermixed in a @try@
    371 statement but the kind of throw must match with kind of handler for it to be
    372 considered as a possible match.
    373 Like termination, when viewed on its own, a @try@ statement with
    374 @catchResume@ clauses simply executes the statements in the @GUARDED_BLOCK@,
    375 and when those are finished, the try statement finishes.
    376 
    377 However, while the guarded statements are being executed, including any invoked
    378 functions, a resumption exception may be thrown. If that exception is not handled by a try
    379 statement further up the stack, the handlers following the try block are now
    380 searched for a matching resumption exception-type from top to bottom.
    381 
    382 Like termination, exception matching checks each @catch@ clasue from top to bottom, if the representation of the thrown exception-type is
    383 the same or a descendant type of the exception types in the @catchResume@ clauses. If
    384 it is the same or a descendant of @EXCEPTION_TYPE@$_i$, then the optional @NAME@$_i$ is
    385 bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$
    386 are executed. If control reaches the end of the handler, the exception is
    387 freed and control continues after the @throwResume@ statement.
    388 
    389 Like termination, if no resumption handler is found during the search, the
    390 default resumption handler visible at the raise is called, which is the best
    391 match at the according to \CFA's overloading rules. This function is passed the
    392 exception given to the raise. After the default handler is run, execution
    393 continues after the @throwResume@ statement.
    394 
    395 There is a global @defaultResumptionHandler@ that is polymorphic over all
    396 resumption and preforms a termination throw on the exception.
    397 The @defaultTerminationHandler@ for that throw is matched at the original
    398 throw statement (the resumption @throwResume@) and it can be customized by
     394% I wonder if there would be some good central place for this.
     395Note that termination handlers and resumption handlers may be used together
     396in a single try statement, intermixing @catch@ and @catchResume@ freely.
     397Each type of handler will only interact with exceptions from the matching
     398type of raise.
     399When a try statement is executed it simply executes the statements in the
     400@GUARDED_BLOCK@ and then finishes.
     401
     402However, while the guarded statements are being executed, including any
     403invoked functions, all the handlers in the statement are now on the search
     404path. If a resumption exception is reported and not handled further up the
     405stack they will be matched against the exception.
     406
     407Exception matching checks the handler in each catch clause in the order
     408they appear, top to bottom. If the representation of the thrown exception type
     409is the same or a descendant of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$
     410(if provided) is bound to a pointer to the exception and the statements in
     411@HANDLER_BLOCK@$_i$ are executed.
     412If control reaches the end of the handler, execution continues after the
     413the raise statement that raised the handled exception.
     414
     415Like termination, if no resumption handler is found, the default handler
     416visible at the throw statement is called. It will use the best match at the
     417call sight according to \CFA's overloading rules. The default handler is
     418passed the exception given to the throw. When the default handler finishes
     419execution continues after the raise statement.
     420
     421There is a global @defaultResumptionHandler@ is polymorphic over all
     422termination exceptions and preforms a termination throw on the exception.
     423The @defaultTerminationHandler@ for that raise is matched at the original
     424raise statement (the resumption @throwResume@) and it can be customized by
    399425introducing a new or better match as well.
    400426
    401 \subsection{Resumption Marking}
     427\subsubsection{Resumption Marking}
    402428A key difference between resumption and termination is that resumption does
    403 not unwind the stack. A side effect is that when a handler is matched
    404 and run its try block (the guarded statements) and every try statement
     429not unwind the stack. A side effect that is that when a handler is matched
     430and run it's try block (the guarded statements) and every try statement
    405431searched before it are still on the stack. This can lead to the recursive
    406432resumption problem.
     
    416442}
    417443\end{cfa}
    418 When this code is executed the guarded @throwResume@ starts a
    419 search and matches the handler in the @catchResume@ clause. The handler is
    420 called and placed on the stack on top of the try-block. The second throw in the handler
    421 searches the same try block and calls another instance of the
     444When this code is executed the guarded @throwResume@ will throw, start a
     445search and match the handler in the @catchResume@ clause. This will be
     446call and placed on the stack on top of the try-block. The second throw then
     447throws and will search the same try block and put call another instance of the
    422448same handler leading to an infinite loop.
    423449
    424 While this situation is trivial and easy to avoid, much more complex cycles
     450This situation is trivial and easy to avoid, but much more complex cycles
    425451can form with multiple handlers and different exception types.
    426452
    427 To prevent this case, examined try statements on the stack are marked, so that
    428 subsequent resumption searches skip over them and continue with the next unmarked section
    429 of the stack.
    430 Unmarking occurs when that exception is handled
    431 or the search completes without finding a handler.
    432 
    433 % This might need a diagram. But it is an important part of the justification
    434 % of the design of the traversal order.
     453To prevent all of these cases we mark try statements on the stack.
     454A try statement is marked when a match check is preformed with it and an
     455exception. The statement will be unmarked when the handling of that exception
     456is completed or the search completes without finding a handler.
     457While a try statement is marked its handlers are never matched, effectify
     458skipping over it to the next try statement.
    435459
    436460\begin{center}
    437 %\begin{verbatim}
    438 %       throwResume2 ----------.
    439 %            |                 |
    440 % generated from handler       |
    441 %            |                 |
    442 %         handler              |
    443 %            |                 |
    444 %        throwResume1 -----.   :
    445 %            |             |   :
    446 %           try            |   : search skip
    447 %            |             |   :
    448 %        catchResume  <----'   :
    449 %            |                 |
    450 %\end{verbatim}
    451 \input{stackMarking}
     461\input{stack-marking}
    452462\end{center}
    453463
    454 The resulting search can be understood by thinking about what is searched for
    455 termination. When a throw happens in a handler, a termination handler
    456 skips everything from the original throw to the original catch because that
    457 part of the stack is unwound. A resumption handler skips the same
    458 section of stack because it is marked.
    459 A throw in a resumption default-handler performs the same search as the original
    460 @throwResume@ because for resumption nothing has been unwound.
    461 
    462 The symmetry between resumption masking and termination searching is why this pattern was picked. Other patterns,
    463 such as marking just the handlers that caught, also work but the
    464 symmetry seems to match programmer intuition.
     464These rules mirror what happens with termination.
     465When a termination throw happens in a handler the search will not look at
     466any handlers from the original throw to the original catch because that
     467part of the stack has been unwound.
     468A resumption raise in the same situation wants to search the entire stack,
     469but it will not try to match the exception with try statements in the section
     470that would have been unwound as they are marked.
     471
     472The symmetry between resumption termination is why this pattern was picked.
     473Other patterns, such as marking just the handlers that caught, also work but
     474lack the symmetry means there are less rules to remember.
    465475
    466476\section{Conditional Catch}
    467 Both termination and resumption handler-clauses can be given an additional
    468 condition to further control which exceptions is handled:
    469 \begin{cfa}
    470 catch (EXCEPTION_TYPE [* NAME] @; CONDITION@)
     477Both termination and resumption handler clauses can be given an additional
     478condition to further control which exceptions they handle:
     479\begin{cfa}
     480catch (EXCEPTION_TYPE * [NAME] ; CONDITION)
    471481\end{cfa}
    472482First, the same semantics is used to match the exception type. Second, if the
    473483exception matches, @CONDITION@ is executed. The condition expression may
    474 reference all names in the scope of the try block and @NAME@
     484reference all names in scope at the beginning of the try block and @NAME@
    475485introduced in the handler clause. If the condition is true, then the handler
    476486matches. Otherwise, the exception search continues as if the exception type
    477487did not match.
    478488
    479 Conditional catch allows fine-gain matching based on object values as well as exception types.
    480 For example, assume the exception hierarchy @OpenFailure@ $\rightarrow$ @CreateFailure@ and these exceptions are raised by function @open@.
    481 \begin{cfa}
    482 try {
    483         f1 = open( ... ); // open raises CreateFailure/OpenFailure
    484         f2 = open( ... ); //    with the associate file
     489The condition matching allows finer matching by allowing the match to check
     490more kinds of information than just the exception type.
     491\begin{cfa}
     492try {
     493        handle1 = open( f1, ... );
     494        handle2 = open( f2, ... );
     495        handle3 = open( f3, ... );
    485496        ...
    486 } catch( CreateFailure * f ; @fd( f ) == f1@ ) {
    487         // only handle IO failure for f1
    488 } catch( OpenFailure * f ; @fd( f ) == f2@ ) {
    489         // only handle IO failure for f2
    490 }
    491 \end{cfa}
    492 Here, matching is very precise on the I/O exception and particular file with an open problem.
    493 This capability cannot be easily mimiced within the handler.
    494 \begin{cfa}
    495 try {
    496         f1 = open( ... );
    497         f2 = open( ... );
    498         ...
    499 } catch( CreateFailure * f ) {
    500         if ( @fd( f ) == f1@ ) ... else // reraise
    501 } catch( OpenFailure * f ) {
    502         if ( @fd( f ) == f2@ ) ... else // reraise
    503 }
    504 \end{cfa}
    505 When an exception @CreateFailure@ is raised, the first handler catches the
    506 derived exception and reraises it if the object is inappropriate. The reraise
    507 immediately terminates the current guarded block, which precludes the handler
    508 for the base exception @OpenFailure@ from consideration for object
    509 @f2@. Therefore, the ``catch first, then reraise'' approach is an incomplete
    510 substitute for conditional catch.
    511 
    512 \section{Reraise}
    513 \label{s:Rethrowing}
    514 \colour{red}{From Andrew: I recommend we talk about why the language doesn't
    515 have rethrows/reraises instead.}
    516 
     497} catch( IOFailure * f ; fd( f ) == f1 ) {
     498        // Only handle IO failure for f1.
     499} catch( IOFailure * f ; fd( f ) == f3 ) {
     500        // Only handle IO failure for f3.
     501}
     502// Can't handle a failure relating to f2 here.
     503\end{cfa}
     504In this example the file that experianced the IO error is used to decide
     505which handler should be run, if any at all.
     506
     507\begin{comment}
     508% I know I actually haven't got rid of them yet, but I'm going to try
     509% to write it as if I had and see if that makes sense:
     510\section{Reraising}
     511\label{s:Reraising}
    517512Within the handler block or functions called from the handler block, it is
    518513possible to reraise the most recently caught exception with @throw@ or
     
    533528is part of an unwound stack frame. To prevent this problem, a new default
    534529handler is generated that does a program-level abort.
    535 \PAB{I don't see how this is different from the normal throw/throwResume.}
     530\end{comment}
     531
     532\subsection{Comparison with Reraising}
     533A more popular way to allow handlers to match in more detail is to reraise
     534the exception after it has been caught if it could not be handled here.
     535On the surface these two features seem interchangable.
     536
     537If we used @throw;@ to start a termination reraise then these two statements
     538would have the same behaviour:
     539\begin{cfa}
     540try {
     541    do_work_may_throw();
     542} catch(exception_t * exc ; can_handle(exc)) {
     543    handle(exc);
     544}
     545\end{cfa}
     546
     547\begin{cfa}
     548try {
     549    do_work_may_throw();
     550} catch(exception_t * exc) {
     551    if (can_handle(exc)) {
     552        handle(exc);
     553    } else {
     554        throw;
     555    }
     556}
     557\end{cfa}
     558If there are further handlers after this handler only the first version will
     559check them. If multiple handlers on a single try block could handle the same
     560exception the translations get more complex but they are equivilantly
     561powerful.
     562
     563Until stack unwinding comes into the picture. In termination handling, a
     564conditional catch happens before the stack is unwound, but a reraise happens
     565afterwards. Normally this might only cause you to loose some debug
     566information you could get from a stack trace (and that can be side stepped
     567entirely by collecting information during the unwind). But for \CFA there is
     568another issue, if the exception isn't handled the default handler should be
     569run at the site of the original raise.
     570
     571There are two problems with this: the site of the original raise doesn't
     572exist anymore and the default handler might not exist anymore. The site will
     573always be removed as part of the unwinding, often with the entirety of the
     574function it was in. The default handler could be a stack allocated nested
     575function removed during the unwind.
     576
     577This means actually trying to pretend the catch didn't happening, continuing
     578the original raise instead of starting a new one, is infeasible.
     579That is the expected behaviour for most languages and we can't replicate
     580that behaviour.
    536581
    537582\section{Finally Clauses}
    538 Finally clauses are used to perform unconditional clean-up when leaving a
    539 scope and appear at the end of a try statement after any catch clauses:
     583\label{s:FinallyClauses}
     584Finally clauses are used to preform unconditional clean-up when leaving a
     585scope and are placed at the end of a try statement after any handler clauses:
    540586\begin{cfa}
    541587try {
     
    548594The @FINALLY_BLOCK@ is executed when the try statement is removed from the
    549595stack, including when the @GUARDED_BLOCK@ finishes, any termination handler
    550 finishes, or during an unwind.
     596finishes or during an unwind.
    551597The only time the block is not executed is if the program is exited before
    552598the stack is unwound.
    553599
    554600Execution of the finally block should always finish, meaning control runs off
    555 the end of the block. This requirement ensures execution always continues as if the
    556 finally clause is not present, \ie @finally@ is for cleanup not changing control
    557 flow. Because of this requirement, local control flow out of the finally block
     601the end of the block. This requirement ensures control always continues as if
     602the finally clause is not present, \ie finally is for cleanup not changing
     603control flow.
     604Because of this requirement, local control flow out of the finally block
    558605is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or
    559606@return@ that causes control to leave the finally block. Other ways to leave
    560607the finally block, such as a long jump or termination are much harder to check,
    561 and at best require additional run-time overhead, and so are
     608and at best requiring additional run-time overhead, and so are only
    562609discouraged.
    563610
    564 Not all languages with exceptions have finally clauses. Notably \Cpp does
    565 without it as destructors serve a similar role. Although destructors and
    566 finally clauses can be used in many of the same areas, they have their own
     611Not all languages with unwinding have finally clauses. Notably \Cpp does
     612without it as descructors serve a similar role. Although destructors and
     613finally clauses can be used in many of the same areas they have their own
    567614use cases like top-level functions and lambda functions with closures.
    568615Destructors take a bit more work to set up but are much easier to reuse while
    569 finally clauses are good for one-off situations and can easily include local information.
     616finally clauses are good for one-off uses and
     617can easily include local information.
    570618
    571619\section{Cancellation}
    572620\label{s:Cancellation}
    573 Cancellation is a stack-level abort, which can be thought of as an
    574 uncatchable termination. It unwinds the entire stack, and when
    575 possible, forwards the cancellation exception to a different stack.
     621Cancellation is a stack-level abort, which can be thought of as as an
     622uncatchable termination. It unwinds the entire current stack, and if
     623possible forwards the cancellation exception to a different stack.
    576624
    577625Cancellation is not an exception operation like termination or resumption.
    578626There is no special statement for starting a cancellation; instead the standard
    579627library function @cancel_stack@ is called passing an exception. Unlike a
    580 throw, this exception is not used in matching only to pass information about
     628raise, this exception is not used in matching only to pass information about
    581629the cause of the cancellation.
    582 (This semantics also means matching cannot fail so there is no default handler.)
    583 
    584 After @cancel_stack@ is called, the exception is copied into the EHM's
    585 memory and the current stack is
     630(This also means matching cannot fail so there is no default handler.)
     631
     632After @cancel_stack@ is called the exception is copied into the EHM's memory
     633and the current stack is
    586634unwound. After that it depends one which stack is being cancelled.
    587635\begin{description}
    588636\item[Main Stack:]
    589637The main stack is the one used by the program main at the start of execution,
    590 and is the only stack in a sequential program. Even in a concurrent program,
    591 the main stack is often used as the environment to start the concurrent threads.
    592 Hence, when the main stack is cancelled there is nowhere else in the program
    593 to go. Hence, after the main stack is unwound, there is a program-level abort.
     638and is the only stack in a sequential program.
     639After the main stack is unwound there is a program-level abort.
     640
     641There are two reasons for this. The first is that it obviously had to do this
     642in a sequential program as there is nothing else to notify and the simplicity
     643of keeping the same behaviour in sequential and concurrent programs is good.
     644Also, even in concurrent programs there is no stack that an innate connection
     645to, so it would have be explicitly managed.
    594646
    595647\item[Thread Stack:]
    596 A thread stack is created for a \CFA @thread@ object or object that satisfies the
    597 @is_thread@ trait. A thread only has two points of communication that must
    598 happen: start and join. A thread must be running to perform a
    599 cancellation (a thread cannot cancel another thread). Therefore, a cancellation must
    600 occur after start and before join, so join is used
    601 for cancellation communication.
    602 After the stack is unwound, the thread halts and waits for
    603 another thread to join with it. The joining thread checks for a cancellation,
    604 and if present, resumes exception @ThreadCancelled@.
    605 
    606 \begin{sloppypar}
    607 There is a subtle difference between the explicit join (@join@ function) and
    608 implicit join (from a @thread@'s destructor call). The explicit join takes the default
    609 handler (@defaultResumptionHandler@) from its calling context, which is used if
    610 the exception is not caught. The implicit join does a program abort instead.
    611 \end{sloppypar}
    612 
    613 \PAB{uC++ does not have these issues, but catch(...) is not working.}
    614 \begin{lstlisting}[language=uC++]
    615 #include <iostream>
    616 using namespace std;
    617 
    618 struct Cl {
    619         ~Cl() { cout << "C" << endl; }
    620 };
    621 _Coroutine C {
    622         void main() {
    623                 Cl c;
    624                 try {
    625                         cancel();
    626                 } catch( ... ) {
    627                         cout << "..." << endl;
    628                 } _Finally {
    629                         cout << "F" << endl;
    630                 }
    631                 }
    632   public:
    633         void mem() { resume(); }
    634 };
    635 _Task T {
    636         void main() {
    637                 Cl c;
    638                 try {
    639                         cancel();
    640                 } catch( ... ) {
    641                         cout << "..." << endl;
    642                 } _Finally {
    643                         cout << "F" << endl;
    644                 }
    645         }
    646 };
    647 int main() {
    648         C c;
    649         cout << "here1" << endl;
    650         c.mem();
    651         cout << "here2" << endl;
    652         {
    653                 T t;
    654         }
    655         cout << "here3" << endl;
    656 }
    657 \end{lstlisting}
    658 
    659 \PAB{This discussion should be its own section.}
    660 This semantics is for safety. If an unwind is triggered while another unwind
    661 is underway only one of them can proceed as they both want to ``consume" the
    662 stack. Letting both try to proceed leads to very undefined behaviour.
    663 Both termination and cancellation involve unwinding and, since the default
    664 @defaultResumptionHandler@ preforms a termination that could more easily
    665 happen in an implicate join inside a destructor. So there is an error message
    666 and an abort instead.
    667 
    668 \todo{Perhaps have a more general disucssion of unwind collisions before
    669 this point.}
    670 
    671 The recommended way to avoid the abort is to handle the initial resumption
    672 from the implicate join. If required you may put an explicate join inside a
    673 finally clause to disable the check and use the local
    674 @defaultResumptionHandler@ instead.
    675 
    676 \item[Coroutine Stack:] A coroutine stack is created for a @coroutine@ object
    677 or object that satisfies the @is_coroutine@ trait. A coroutine only knows of
    678 two other coroutines, its starter and its last resumer. Of the two the last
    679 resumer has the tightest coupling to the coroutine it activated and the most
    680 up-to-date information.
    681 
    682 Hence, cancellation of the active coroutine is forwarded to the last resumer
    683 after the stack is unwound. When the resumer restarts, it resumes exception
    684 @CoroutineCancelled@, which is polymorphic over the coroutine type and has a
    685 pointer to the cancelled coroutine.
    686 
    687 The resume function also has an assertion that the @defaultResumptionHandler@
    688 for the exception. So it will use the default handler like a regular throw.
     648A thread stack is created for a \CFA @thread@ object or object that satisfies
     649the @is_thread@ trait.
     650After a thread stack is unwound there exception is stored until another
     651thread attempts to join with it. Then the exception @ThreadCancelled@,
     652which stores a reference to the thread and to the exception passed to the
     653cancellation, is reported from the join.
     654There is one difference between an explicit join (with the @join@ function)
     655and an implicit join (from a destructor call). The explicit join takes the
     656default handler (@defaultResumptionHandler@) from its calling context while
     657the implicit join provides its own which does a program abort if the
     658@ThreadCancelled@ exception cannot be handled.
     659
     660Communication is done at join because a thread only has to have to points of
     661communication with other threads: start and join.
     662Since a thread must be running to perform a cancellation (and cannot be
     663cancelled from another stack), the cancellation must be after start and
     664before the join. So join is the one that we will use.
     665
     666% TODO: Find somewhere to discuss unwind collisions.
     667The difference between the explicit and implicit join is for safety and
     668debugging. It helps prevent unwinding collisions by avoiding throwing from
     669a destructor and prevents cascading the error across multiple threads if
     670the user is not equipped to deal with it.
     671Also you can always add an explicit join if that is the desired behaviour.
     672
     673\item[Coroutine Stack:]
     674A coroutine stack is created for a @coroutine@ object or object that
     675satisfies the @is_coroutine@ trait.
     676After a coroutine stack is unwound control returns to the resume function
     677that most recently resumed it. The resume statement reports a
     678@CoroutineCancelled@ exception, which contains a references to the cancelled
     679coroutine and the exception used to cancel it.
     680The resume function also takes the @defaultResumptionHandler@ from the
     681caller's context and passes it to the internal report.
     682
     683A coroutine knows of two other coroutines, its starter and its last resumer.
     684The starter has a much more distant connection while the last resumer just
     685(in terms of coroutine state) called resume on this coroutine, so the message
     686is passed to the latter.
    689687\end{description}
    690 
    691 \PAB{You should have more test programs that compare \CFA EHM to uC++ EHM.}
  • doc/theses/andrew_beach_MMath/uw-ethesis.tex

    r665edf40 r73d0c54a  
    7474% ======================================================================
    7575%   D O C U M E N T   P R E A M B L E
    76 % Specify the document class, default style attributes, page dimensions, etc.
    77 % For hyperlinked PDF, suitable for viewing on a computer, use this:
    78 \documentclass[letterpaper,12pt,titlepage,oneside,final]{book}
    79 
    80 % For PDF, suitable for double-sided printing, change the PrintVersion
    81 % variable below to "true" and use this \documentclass line instead of the
    82 % one above:
    83 %\documentclass[letterpaper,12pt,titlepage,openright,twoside,final]{book}
    84 
    85 \usepackage{etoolbox}
     76\RequirePackage{etoolbox}
     77
     78% Control if this for print (set true) or will stay digital (default).
     79% Print is two sided, digital uses more colours.
     80\newtoggle{printversion}
     81%\toggletrue{printversion}
     82
     83\iftoggle{printversion}{%
     84  \documentclass[letterpaper,12pt,titlepage,openright,twoside,final]{book}
     85}{%
     86  \documentclass[letterpaper,12pt,titlepage,oneside,final]{book}
     87}
    8688
    8789% Some LaTeX commands I define for my own nomenclature.
     
    9496% Anything defined here may be redefined by packages added below...
    9597
    96 % This package allows if-then-else control structures.
    97 \usepackage{ifthen}
    98 \newboolean{PrintVersion}
    99 \setboolean{PrintVersion}{false}
    100 % CHANGE THIS VALUE TO "true" as necessary, to improve printed results for
    101 % hard copies by overriding some options of the hyperref package, called below.
    102 
    103 %\usepackage{nomencl} % For a nomenclature (optional; available from ctan.org)
     98% For a nomenclature (optional; available from ctan.org)
     99%\usepackage{nomencl}
    104100% Lots of math symbols and environments
    105101\usepackage{amsmath,amssymb,amstext}
    106 % For including graphics N.B. pdftex graphics driver
    107 %\usepackage[pdftex]{graphicx}
     102% For including graphics (must match graphics driver)
    108103\usepackage{epic,eepic}
    109104\usepackage{graphicx}
     
    113108\usepackage{todonotes}
    114109
    115 
    116110% Hyperlinks make it very easy to navigate an electronic document.
    117111% In addition, this is where you should specify the thesis title and author as
     
    119113% Use the "hyperref" package
    120114% N.B. HYPERREF MUST BE THE LAST PACKAGE LOADED; ADD ADDITIONAL PKGS ABOVE
    121 %\usepackage[pdftex,pagebackref=true]{hyperref} % with basic options
    122 \usepackage[pagebackref=true]{hyperref} % with basic options
    123 %\usepackage[pdftex,pagebackref=true]{hyperref}
     115\usepackage[pagebackref=true]{hyperref}
    124116% N.B. pagebackref=true provides links back from the References to the body
    125117% text. This can cause trouble for printing.
     
    131123    pdffitwindow=false,     % window fit to page when opened
    132124    pdfstartview={FitH},    % fits the width of the page to the window
    133 %    pdftitle={uWaterloo\ LaTeX\ Thesis\ Template}, % title: CHANGE THIS TEXT!
    134 %    pdfauthor={Author},    % author: CHANGE THIS TEXT! and uncomment this line
    135 %    pdfsubject={Subject},  % subject: CHANGE THIS TEXT! and uncomment this line
    136 %    pdfkeywords={keyword1} {key2} {key3}, % optional list of keywords
    137125    pdfnewwindow=true,      % links in new window
    138126    colorlinks=true,        % false: boxed links; true: colored links
    139     linkcolor=blue,         % color of internal links
    140     citecolor=green,        % color of links to bibliography
    141     filecolor=magenta,      % color of file links
    142     urlcolor=cyan           % color of external links
    143127}
    144 % for improved print quality, change some hyperref options
    145 \ifthenelse{\boolean{PrintVersion}}{
    146 \hypersetup{    % override some previously defined hyperref options
    147 %    colorlinks,%
    148     citecolor=black,%
    149     filecolor=black,%
    150     linkcolor=black,%
    151     urlcolor=black}
    152 }{} % end of ifthenelse (no else)
     128\iftoggle{printversion}{
     129  \hypersetup{
     130    citecolor=black,        % colour of links to bibliography
     131    filecolor=black,        % colour of file links
     132    linkcolor=black,        % colour of internal links
     133    urlcolor=black,         % colour of external links
     134  }
     135}{ % Digital Version
     136  \hypersetup{
     137    citecolor=green,
     138    filecolor=magenta,
     139    linkcolor=blue,
     140    urlcolor=cyan,
     141  }
     142}
     143
     144\hypersetup{
     145  pdftitle={Exception Handling in Cforall},
     146  pdfauthor={Andrew James Beach},
     147  pdfsubject={Computer Science},
     148  pdfkeywords={programming languages} {exceptions}
     149      {language design} {language implementation},
     150}
    153151
    154152% Exception to the rule of hyperref being the last add-on package
     
    220218\pdfstringdefDisableCommands{\def\Cpp{C++}}
    221219
     220% Wrappers for inline code snippits.
     221\newrobustcmd*\codeCFA[1]{\lstinline[language=CFA]{#1}}
     222\newrobustcmd*\codeC[1]{\lstinline[language=C]{#1}}
     223\newrobustcmd*\codeCpp[1]{\lstinline[language=C++]{#1}}
     224\newrobustcmd*\codePy[1]{\lstinline[language=Python]{#1}}
     225
    222226% Colour text, formatted in LaTeX style instead of TeX style.
    223227\newcommand*\colour[2]{{\color{#1}#2}}
  • doc/user/user.tex

    r665edf40 r73d0c54a  
    1111%% Created On       : Wed Apr  6 14:53:29 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Sat Mar 27 09:55:55 2021
    14 %% Update Count     : 4796
     13%% Last Modified On : Tue Apr 20 23:25:56 2021
     14%% Update Count     : 4888
    1515%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    1616
     
    6666% math escape $...$ (dollar symbol)
    6767\input{common}                                          % common CFA document macros
     68\setlength{\gcolumnposn}{3in}
    6869\CFAStyle                                                                                               % use default CFA format-style
    6970\lstset{language=CFA}                                                                   % CFA default lnaguage
     
    21662167\section{Enumeration}
    21672168
    2168 An \newterm{enumeration} is a compile-time mechanism to give names to constants.
    2169 There is no runtime manifestation of an enumeration.
    2170 Their purpose is code-readability and maintenance -- changing an enum's value automatically updates all name usages during compilation.
    2171 
    2172 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.
    2173 \begin{cfa}
    2174 enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; // enumeration type definition, set of 7 names
     2169An \newterm{enumeration} is a compile-time mechanism to alias names to constants, like ©typedef© is a mechanism to alias names to types.
     2170Its 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.
     2171
     2172An enumeration type is a set of names, each called an \newterm{enumeration constant} (shortened to \newterm{enum}) aliased to a fixed value (constant).
     2173\begin{cfa}
     2174enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; // enumeration type definition, set of 7 names & values
    21752175Days days = Mon; // enumeration type declaration and initialization
    21762176\end{cfa}
    2177 The set of enums are injected into the scope of the definition and use the variable namespace.
     2177The set of enums are injected into the variable namespace at the definition scope.
    21782178Hence, enums may be overloaded with enum/variable/function names.
    21792179\begin{cfa}
     
    21832183double Bar;                     $\C{// overload Foo.Bar, Goo.Bar}\CRT$
    21842184\end{cfa}
    2185 An anonymous enumeration is used to inject enums with specific values into a scope:
     2185An anonymous enumeration injects enums with specific values into a scope.
    21862186\begin{cfa}
    21872187enum { Prime = 103, BufferSize = 1024 };
    21882188\end{cfa}
    2189 An enumeration is better than using the C \Index{preprocessor}
     2189An enumeration is better than using C \Index{preprocessor} or constant declarations.
     2190\begin{cquote}
     2191\begin{tabular}{@{}l@{\hspace{4em}}l@{}}
    21902192\begin{cfa}
    21912193#define Mon 0
     
    21932195#define Sun 6
    21942196\end{cfa}
    2195 or C constant declarations
    2196 \begin{cfa}
    2197 const int Mon = 0, ..., Sun = 6;
    2198 \end{cfa}
     2197&
     2198\begin{cfa}
     2199const int Mon = 0,
     2200                         ...,
     2201                         Sun = 6;
     2202\end{cfa}
     2203\end{tabular}
     2204\end{cquote}
    21992205because the enumeration is succinct, has automatic numbering, can appear in ©case© labels, does not use storage, and is part of the language type-system.
    22002206Finally, the type of an enum is implicitly or explicitly specified and the constant value can be implicitly or explicitly specified.
     
    22042210\subsection{Enum type}
    22052211
    2206 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.
    2207 \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.
     2212The type of enums can be any type, and an enum's value comes from this type.
     2213Because 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).
     2214Therefore, 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;
     2215there is no mechanism to print the enum name.
     2216
    22082217The default enum type is ©int©.
    22092218Hence, ©Days© is the set type ©Mon©, ©Tue©, ...\,, ©Sun©, while the type of each enum is ©int© and each enum represents a fixed integral value.
    22102219If no values are specified for an integral enum type, the enums are automatically numbered by one from left to right starting at zero.
    22112220Hence, the value of enum ©Mon© is 0, ©Tue© is 1, ...\,, ©Sun© is 6.
    2212 If a value is specified, numbering continues by one from that value.
    2213 It an enum value is an expression, the compiler performs constant-folding to obtain a constant value.
    2214 
    2215 Other integral types with associated values can be explicitly specified.
     2221If an enum value is specified, numbering continues by one from that value for subsequent unnumbered enums.
     2222If an enum value is an expression, the compiler performs constant-folding to obtain a constant value.
     2223
     2224\CFA allows other integral types with associated values.
    22162225\begin{cfa}
    22172226enum( @char@ ) Letter { A @= 'A'@,  B,  C,  I @= 'I'@,  J,  K };
     
    22192228\end{cfa}
    22202229For 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©.
    2221 Note, an enum is an immutable constant, \ie ©A = B© is disallowed;
    2222 by transitivity, an enum's type is implicitly ©const©.
    2223 Hence, a constant/enum cannot appear in a mutuable context nor is a constant/enum addressable (rvalue).
    2224 
    2225 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©.
     2230
     2231Non-integral enum types must be explicitly initialized, \eg ©double© is not automatically numbered by one.
    22262232\begin{cfa}
    22272233// non-integral numeric
    2228 enum( double ) Math { PI_2 = 1.570796, PI = 3.141597,  E = 2.718282 }
     2234enum( @double@ ) Math { PI_2 = 1.570796, PI = 3.141597,  E = 2.718282 }
    22292235// pointer
    2230 enum( char * ) Name { Fred = "Fred",  Mary = "Mary",  Jane = "Jane" };
     2236enum( @char *@ ) Name { Fred = "Fred",  Mary = "Mary",  Jane = "Jane" };
    22312237int i, j, k;
    2232 enum( int * ) ptr { I = &i,  J = &j,  K = &k };
    2233 enum( int & ) ref { I = i,  J = j,  K = k };
     2238enum( @int *@ ) ptr { I = &i,  J = &j,  K = &k };
     2239enum( @int &@ ) ref { I = i,  J = j,  K = k };
    22342240// tuple
    2235 enum( [int, int] ) { T = [ 1, 2 ] };
     2241enum( @[int, int]@ ) { T = [ 1, 2 ] };
    22362242// function
    22372243void f() {...}   void g() {...}
    2238 enum( void (*)() ) funs { F = f,  F = g };
     2244enum( @void (*)()@ ) funs { F = f,  F = g };
    22392245// aggregate
    22402246struct S { int i, j; };
    2241 enum( S ) s { A = { 3,  4 }, B = { 7,  8 } };
     2247enum( @S@ ) s { A = { 3,  4 }, B = { 7,  8 } };
    22422248// enumeration
    2243 enum( Letter ) Greek { Alph = A, Beta = B, /* more enums */  }; // alphabet intersection
     2249enum( @Letter@ ) Greek { Alph = A, Beta = B, /* more enums */  }; // alphabet intersection
    22442250\end{cfa}
    22452251Enumeration ©Greek© may have more or less enums than ©Letter©, but the enum values \emph{must} be from ©Letter©.
     
    22532259m = Alph;               $\C{// {\color{red}disallowed}}$
    22542260m = 3.141597;   $\C{// {\color{red}disallowed}}$
    2255 d = E;                  $\C{// allowed, conversion to base type}$
    2256 d = m;                  $\C{// {\color{red}disallowed}}$
     2261d = m;                  $\C{// allowed}$
    22572262d = Alph;               $\C{// {\color{red}disallowed}}$
    22582263Letter l = A;   $\C{// allowed}$
     
    22632268
    22642269A constructor \emph{cannot} be used to initialize enums because a constructor executes at runtime.
    2265 A fallback is to substitute C-style initialization overriding the constructor with ©@=©.
    2266 \begin{cfa}
    2267 enum( struct vec3 ) Axis { Up $@$= { 1, 0, 0 }, Left $@$= ..., Front $@$= ... }
     2270A fallback is explicit C-style initialization using ©@=©.
     2271\begin{cfa}
     2272enum( struct vec3 ) Axis { Up $@$= { 1, 0, 0 }, Left $@$= { 0, 1, 0 }, Front $@$= { 0, 0, 1 } }
    22682273\end{cfa}
    22692274Finally, enumeration variables are assignable and comparable only if the appropriate operators are defined for its enum type.
     
    22742279\Index{Plan-9}\index{inheritance!enumeration} inheritance may be used with enumerations.
    22752280\begin{cfa}
    2276 enum( const char * ) Name2 { @inline Name@, Jack = "Jack", Jill = "Jill" };
    2277 enum @/* inferred */@  Name3 { @inline Name@, @inline Name2@, Sue = "Sue", Tom = "Tom" };
     2281enum( char * ) Name2 { @inline Name@, Jack = "Jack", Jill = "Jill" };
     2282enum @/* inferred */@  Name3 { @inline Name2@, Sue = "Sue", Tom = "Tom" };
    22782283\end{cfa}
    22792284Enumeration ©Name2© inherits all the enums and their values from enumeration ©Name© by containment, and a ©Name© enumeration is a subtype of enumeration ©Name2©.
     
    22812286The enum type for the inheriting type must be the same as the inherited type;
    22822287hence the enum type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for ©Name3©.
    2283 When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
     2288When 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©.
    22842289
    22852290Specifically, the inheritance relationship for ©Name©s is:
     
    23012306j( Fred );    j( Jill );    j( Sue );    j( 'W' );
    23022307\end{cfa}
    2303 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.
     2308Note, 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.
    23042309
    23052310Enums cannot be created at runtime, so inheritence problems, such as contra-variance do not apply.
     
    23132318\begin{cfa}
    23142319// Fred is a subset of char *
    2315 enum char * Fred { A = "A", B = "B", C = "C" };
     2320enum( char *) Fred { A = "A", B = "B", C = "C" };
    23162321// Jack is a subset of Fred
    2317 enum enum Fred Jack { W = A, Y = C};
     2322enum( enum Fred ) Jack { W = A, Y = C};
    23182323// Mary is a superset of Fred
    23192324enum Mary { inline Fred, D = "hello" };
     
    41684173
    41694174The 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.
    4170 For ©_Bool© type, the constants are ©true© and ©false©.
     4175For ©bool© type, the constants are ©true© and ©false©.
    41714176For integral types, any number of digits, optionally preceded by a sign (©+© or ©-©), where a
    41724177\begin{itemize}
     
    45804585In 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.
    45814586However, 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.
    4582 Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©.
     4587Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©bool©.
    45834588
    45844589Why just 0 and 1? Why not other integers? No other integers have special status in C.
     
    50455050\begin{figure}
    50465051\begin{cfa}
    5047 #include <fstream>
    5048 #include <coroutine>
    5049 
    5050 coroutine Fibonacci {
     5052#include <fstream.hfa>
     5053#include @<coroutine.hfa>@
     5054
     5055@coroutine@ Fibonacci {
    50515056        int fn; $\C{// used for communication}$
    50525057};
    5053 void ?{}( Fibonacci * this ) {
    5054         this->fn = 0;
    5055 }
    5056 void main( Fibonacci * this ) {
     5058
     5059void main( Fibonacci & fib ) with( fib ) { $\C{// called on first resume}$
    50575060        int fn1, fn2; $\C{// retained between resumes}$
    5058         this->fn = 0; $\C{// case 0}$
    5059         fn1 = this->fn;
    5060         suspend(); $\C{// return to last resume}$
    5061 
    5062         this->fn = 1; $\C{// case 1}$
    5063         fn2 = fn1;
    5064         fn1 = this->fn;
    5065         suspend(); $\C{// return to last resume}$
    5066 
    5067         for ( ;; ) { $\C{// general case}$
    5068                 this->fn = fn1 + fn2;
    5069                 fn2 = fn1;
    5070                 fn1 = this->fn;
    5071                 suspend(); $\C{// return to last resume}$
    5072         } // for
    5073 }
    5074 int next( Fibonacci * this ) {
    5075         resume( this ); $\C{// transfer to last suspend}$
    5076         return this->fn;
     5061        fn = 0;  fn1 = fn; $\C{// 1st case}$
     5062        @suspend;@ $\C{// restart last resume}$
     5063        fn = 1;  fn2 = fn1;  fn1 = fn; $\C{// 2nd case}$
     5064        @suspend;@ $\C{// restart last resume}$
     5065        for () {
     5066                fn = fn1 + fn2;  fn2 = fn1;  fn1 = fn; $\C{// general case}$
     5067                @suspend;@ $\C{// restart last resume}$
     5068        }
     5069}
     5070int next( Fibonacci & fib ) with( fib ) {
     5071        @resume( fib );@ $\C{// restart last suspend}$
     5072        return fn;
    50775073}
    50785074int main() {
    50795075        Fibonacci f1, f2;
    5080         for ( int i = 1; i <= 10; i += 1 ) {
    5081                 sout | next( &f1 ) | ' ' | next( &f2 );
    5082         } // for
    5083 }
    5084 \end{cfa}
     5076        for ( 10 ) { $\C{// print N Fibonacci values}$
     5077                sout | next( f1 ) | next( f2 );
     5078        }
     5079}
     5080\end{cfa}
     5081\vspace*{-5pt}
    50855082\caption{Fibonacci Coroutine}
    50865083\label{f:FibonacciCoroutine}
     
    51085105\begin{figure}
    51095106\begin{cfa}
    5110 #include <fstream>
    5111 #include <kernel>
    5112 #include <monitor>
    5113 #include <thread>
    5114 
    5115 monitor global_t {
    5116         int value;
    5117 };
    5118 
    5119 void ?{}(global_t * this) {
    5120         this->value = 0;
    5121 }
    5122 
    5123 static global_t global;
    5124 
    5125 void increment3( global_t * mutex this ) {
    5126         this->value += 1;
    5127 }
    5128 void increment2( global_t * mutex this ) {
    5129         increment3( this );
    5130 }
    5131 void increment( global_t * mutex this ) {
    5132         increment2( this );
    5133 }
     5107#include <fstream.hfa>
     5108#include @<thread.hfa>@
     5109
     5110@monitor@ AtomicCnt { int counter; };
     5111void ?{}( AtomicCnt & c, int init = 0 ) with(c) { counter = init; }
     5112int inc( AtomicCnt & @mutex@ c, int inc = 1 ) with(c) { return counter += inc; }
     5113int dec( AtomicCnt & @mutex@ c, int dec = 1 ) with(c) { return counter -= dec; }
     5114forall( ostype & | ostream( ostype ) ) { $\C{// print any stream}$
     5115        ostype & ?|?( ostype & os, AtomicCnt c ) { return os | c.counter; }
     5116        void ?|?( ostype & os, AtomicCnt c ) { (ostype &)(os | c.counter); ends( os ); }
     5117}
     5118
     5119AtomicCnt global; $\C{// shared}$
    51345120
    51355121thread MyThread {};
    5136 
    5137 void main( MyThread* this ) {
    5138         for(int i = 0; i < 1_000_000; i++) {
    5139                 increment( &global );
     5122void main( MyThread & ) {
     5123        for ( i; 100_000 ) {
     5124                inc( global );
     5125                dec( global );
    51405126        }
    51415127}
    5142 int main(int argc, char* argv[]) {
    5143         processor p;
     5128int main() {
     5129        enum { Threads = 4 };
     5130        processor p[Threads - 1]; $\C{// + starting processor}$
    51445131        {
    5145                 MyThread f[4];
     5132                MyThread t[Threads];
    51465133        }
    5147         sout | global.value;
     5134        sout | global; $\C{// print 0}$
    51485135}
    51495136\end{cfa}
    51505137\caption{Atomic-Counter Monitor}
    5151 \caption{f:AtomicCounterMonitor}
     5138\label{f:AtomicCounterMonitor}
    51525139\end{figure}
    51535140
     
    73207307[ int, long double ] remquo( long double, long double );
    73217308
    7322 float div( float, float, int * );$\indexc{div}$ $\C{// alternative name for remquo}$
    7323 double div( double, double, int * );
    7324 long double div( long double, long double, int * );
    73257309[ int, float ] div( float, float );
    73267310[ int, double ] div( double, double );
     
    73837367long double _Complex log( long double _Complex );
    73847368
    7385 float log2( float );$\indexc{log2}$
     7369int log2( unsigned int );$\indexc{log2}$
     7370long int log2( unsigned long int );
     7371long long int log2( unsigned long long int )
     7372float log2( float );
    73867373double log2( double );
    73877374long double log2( long double );
     
    75657552\leavevmode
    75667553\begin{cfa}[aboveskip=0pt,belowskip=0pt]
     7554// n / align * align
     7555signed char floor( signed char n, signed char align );
     7556unsigned char floor( unsigned char n, unsigned char align );
     7557short int floor( short int n, short int align );
     7558unsigned short int floor( unsigned short int n, unsigned short int align );
     7559int floor( int n, int align );
     7560unsigned int floor( unsigned int n, unsigned int align );
     7561long int floor( long int n, long int align );
     7562unsigned long int floor( unsigned long int n, unsigned long int align );
     7563long long int floor( long long int n, long long int align );
     7564unsigned long long int floor( unsigned long long int n, unsigned long long int align );
     7565
     7566// (n + (align - 1)) / align
     7567signed char ceiling_div( signed char n, char align );
     7568unsigned char ceiling_div( unsigned char n, unsigned char align );
     7569short int ceiling_div( short int n, short int align );
     7570unsigned short int ceiling_div( unsigned short int n, unsigned short int align );
     7571int ceiling_div( int n, int align );
     7572unsigned int ceiling_div( unsigned int n, unsigned int align );
     7573long int ceiling_div( long int n, long int align );
     7574unsigned long int ceiling_div( unsigned long int n, unsigned long int align );
     7575long long int ceiling_div( long long int n, long long int align );
     7576unsigned long long int ceiling_div( unsigned long long int n, unsigned long long int align );
     7577
     7578// floor( n + (n % align != 0 ? align - 1 : 0), align )
     7579signed char ceiling( signed char n, signed char align );
     7580unsigned char ceiling( unsigned char n, unsigned char align );
     7581short int ceiling( short int n, short int align );
     7582unsigned short int ceiling( unsigned short int n, unsigned short int align );
     7583int ceiling( int n, int align );
     7584unsigned int ceiling( unsigned int n, unsigned int align );
     7585long int ceiling( long int n, long int align );
     7586unsigned long int ceiling( unsigned long int n, unsigned long int align );
     7587long long int ceiling( long long int n, long long int align );
     7588unsigned long long int ceiling( unsigned long long int n, unsigned long long int align );
     7589
    75677590float floor( float );$\indexc{floor}$
    75687591double floor( double );
     
    76677690\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    76687691struct Duration {
    7669         int64_t tv; $\C{// nanoseconds}$
     7692        int64_t tn; $\C{// nanoseconds}$
    76707693};
    76717694
    76727695void ?{}( Duration & dur );
    76737696void ?{}( Duration & dur, zero_t );
     7697void ?{}( Duration & dur, timeval t )
     7698void ?{}( Duration & dur, timespec t )
    76747699
    76757700Duration ?=?( Duration & dur, zero_t );
     7701Duration ?=?( Duration & dur, timeval t )
     7702Duration ?=?( Duration & dur, timespec t )
    76767703
    76777704Duration +?( Duration rhs );
     
    76957722Duration ?%=?( Duration & lhs, Duration rhs );
    76967723
    7697 _Bool ?==?( Duration lhs, Duration rhs );
    7698 _Bool ?!=?( Duration lhs, Duration rhs );
    7699 _Bool ?<? ( Duration lhs, Duration rhs );
    7700 _Bool ?<=?( Duration lhs, Duration rhs );
    7701 _Bool ?>? ( Duration lhs, Duration rhs );
    7702 _Bool ?>=?( Duration lhs, Duration rhs );
    7703 
    7704 _Bool ?==?( Duration lhs, zero_t );
    7705 _Bool ?!=?( Duration lhs, zero_t );
    7706 _Bool ?<? ( Duration lhs, zero_t );
    7707 _Bool ?<=?( Duration lhs, zero_t );
    7708 _Bool ?>? ( Duration lhs, zero_t );
    7709 _Bool ?>=?( Duration lhs, zero_t );
     7724bool ?==?( Duration lhs, zero_t );
     7725bool ?!=?( Duration lhs, zero_t );
     7726bool ?<? ( Duration lhs, zero_t );
     7727bool ?<=?( Duration lhs, zero_t );
     7728bool ?>? ( Duration lhs, zero_t );
     7729bool ?>=?( Duration lhs, zero_t );
     7730
     7731bool ?==?( Duration lhs, Duration rhs );
     7732bool ?!=?( Duration lhs, Duration rhs );
     7733bool ?<? ( Duration lhs, Duration rhs );
     7734bool ?<=?( Duration lhs, Duration rhs );
     7735bool ?>? ( Duration lhs, Duration rhs );
     7736bool ?>=?( Duration lhs, Duration rhs );
    77107737
    77117738Duration abs( Duration rhs );
     
    77347761int64_t ?`w( Duration dur );
    77357762
     7763double ?`dns( Duration dur );
     7764double ?`dus( Duration dur );
     7765double ?`dms( Duration dur );
     7766double ?`ds( Duration dur );
     7767double ?`dm( Duration dur );
     7768double ?`dh( Duration dur );
     7769double ?`dd( Duration dur );
     7770double ?`dw( Duration dur );
     7771
    77367772Duration max( Duration lhs, Duration rhs );
    77377773Duration min( Duration lhs, Duration rhs );
     7774
     7775forall( ostype & | ostream( ostype ) ) ostype & ?|?( ostype & os, Duration dur );
    77387776\end{cfa}
    77397777
     
    77467784\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    77477785void ?{}( timeval & t );
     7786void ?{}( timeval & t, zero_t );
    77487787void ?{}( timeval & t, time_t sec, suseconds_t usec );
    77497788void ?{}( timeval & t, time_t sec );
    7750 void ?{}( timeval & t, zero_t );
    77517789void ?{}( timeval & t, Time time );
    77527790
     
    77547792timeval ?+?( timeval & lhs, timeval rhs );
    77557793timeval ?-?( timeval & lhs, timeval rhs );
    7756 _Bool ?==?( timeval lhs, timeval rhs );
    7757 _Bool ?!=?( timeval lhs, timeval rhs );
     7794bool ?==?( timeval lhs, timeval rhs );
     7795bool ?!=?( timeval lhs, timeval rhs );
    77587796\end{cfa}
    77597797
     
    77667804\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    77677805void ?{}( timespec & t );
     7806void ?{}( timespec & t, zero_t );
    77687807void ?{}( timespec & t, time_t sec, __syscall_slong_t nsec );
    77697808void ?{}( timespec & t, time_t sec );
    7770 void ?{}( timespec & t, zero_t );
    77717809void ?{}( timespec & t, Time time );
    77727810
     
    77747812timespec ?+?( timespec & lhs, timespec rhs );
    77757813timespec ?-?( timespec & lhs, timespec rhs );
    7776 _Bool ?==?( timespec lhs, timespec rhs );
    7777 _Bool ?!=?( timespec lhs, timespec rhs );
     7814bool ?==?( timespec lhs, timespec rhs );
     7815bool ?!=?( timespec lhs, timespec rhs );
    77787816\end{cfa}
    77797817
     
    77977835\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    77987836struct Time {
    7799         uint64_t tv; $\C{// nanoseconds since UNIX epoch}$
     7837        uint64_t tn; $\C{// nanoseconds since UNIX epoch}$
    78007838};
    78017839
    78027840void ?{}( Time & time );
    78037841void ?{}( Time & time, zero_t );
     7842void ?{}( Time & time, timeval t );
     7843void ?{}( Time & time, timespec t );
    78047844
    78057845Time ?=?( Time & time, zero_t );
    7806 
    7807 void ?{}( Time & time, timeval t );
    78087846Time ?=?( Time & time, timeval t );
    7809 
    7810 void ?{}( Time & time, timespec t );
    78117847Time ?=?( Time & time, timespec t );
    78127848
     
    78187854Time ?-?( Time lhs, Duration rhs );
    78197855Time ?-=?( Time & lhs, Duration rhs );
    7820 _Bool ?==?( Time lhs, Time rhs );
    7821 _Bool ?!=?( Time lhs, Time rhs );
    7822 _Bool ?<?( Time lhs, Time rhs );
    7823 _Bool ?<=?( Time lhs, Time rhs );
    7824 _Bool ?>?( Time lhs, Time rhs );
    7825 _Bool ?>=?( Time lhs, Time rhs );
     7856bool ?==?( Time lhs, Time rhs );
     7857bool ?!=?( Time lhs, Time rhs );
     7858bool ?<?( Time lhs, Time rhs );
     7859bool ?<=?( Time lhs, Time rhs );
     7860bool ?>?( Time lhs, Time rhs );
     7861bool ?>=?( Time lhs, Time rhs );
     7862
     7863int64_t ?`ns( Time t );
    78267864
    78277865char * yy_mm_dd( Time time, char * buf );
    7828 char * ?`ymd( Time time, char * buf ) { // short form
    7829         return yy_mm_dd( time, buf );
    7830 } // ymd
     7866char * ?`ymd( Time time, char * buf ); // short form
    78317867
    78327868char * mm_dd_yy( Time time, char * buf );
    7833 char * ?`mdy( Time time, char * buf ) { // short form
    7834         return mm_dd_yy( time, buf );
    7835 } // mdy
     7869char * ?`mdy( Time time, char * buf ); // short form
    78367870
    78377871char * dd_mm_yy( Time time, char * buf );
    7838 char * ?`dmy( Time time, char * buf ) { // short form
    7839         return dd_mm_yy( time, buf );;
    7840 } // dmy
     7872char * ?`dmy( Time time, char * buf ); // short form
    78417873
    78427874size_t strftime( char * buf, size_t size, const char * fmt, Time time );
    7843 forall( dtype ostype | ostream( ostype ) ) ostype & ?|?( ostype & os, Time time );
     7875
     7876forall( ostype & | ostream( ostype ) ) ostype & ?|?( ostype & os, Time time );
    78447877\end{cfa}
    78457878
     
    78677900\leavevmode
    78687901\begin{cfa}[aboveskip=0pt,belowskip=0pt]
    7869 struct Clock {
    7870         Duration offset; $\C{// for virtual clock: contains offset from real-time}$
    7871         int clocktype; $\C{// implementation only -1 (virtual), CLOCK\_REALTIME}$
     7902struct Clock { $\C{// virtual clock}$
     7903        Duration offset; $\C{// offset from computer real-time}$
    78727904};
    78737905
    7874 void resetClock( Clock & clk );
    7875 void resetClock( Clock & clk, Duration adj );
    7876 void ?{}( Clock & clk );
    7877 void ?{}( Clock & clk, Duration adj );
    7878 
    7879 Duration getResNsec(); $\C{// with nanoseconds}$
    7880 Duration getRes(); $\C{// without nanoseconds}$
    7881 
    7882 Time getTimeNsec(); $\C{// with nanoseconds}$
    7883 Time getTime(); $\C{// without nanoseconds}$
    7884 Time getTime( Clock & clk );
    7885 Time ?()( Clock & clk );
    7886 timeval getTime( Clock & clk );
    7887 tm getTime( Clock & clk );
     7906void ?{}( Clock & clk ); $\C{// create no offset}$
     7907void ?{}( Clock & clk, Duration adj ); $\C{// create with offset}$
     7908void reset( Clock & clk, Duration adj ); $\C{// change offset}$
     7909
     7910Duration resolutionHi(); $\C{// clock resolution in nanoseconds (fine)}$
     7911Duration resolution(); $\C{// clock resolution without nanoseconds (coarse)}$
     7912
     7913Time timeHiRes(); $\C{// real time with nanoseconds}$
     7914Time time(); $\C{// real time without nanoseconds}$
     7915Time time( Clock & clk ); $\C{// real time for given clock}$
     7916Time ?()( Clock & clk ); $\C{//\ \ \ \ alternative syntax}$
     7917timeval time( Clock & clk ); $\C{// convert to C time format}$
     7918tm time( Clock & clk );
     7919Duration processor(); $\C{// non-monotonic duration of kernel thread}$
     7920Duration program(); $\C{// non-monotonic duration of program CPU}$
     7921Duration boot(); $\C{// monotonic duration since computer boot}$
    78887922\end{cfa}
    78897923
     
    80568090forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype * os, Int mp );
    80578091\end{cfa}
    8058 
    8059 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}.
     8092\VRef[Figure]{f:MultiPrecisionFactorials} shows \CFA and C factorial programs using the GMP interfaces.
    80608093(Compile with flag \Indexc{-lgmp} to link with the GMP library.)
     8094
     8095\begin{figure}
    80618096\begin{cquote}
    80628097\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
    8063 \multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}}    & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
     8098\multicolumn{1}{@{}c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}@{}}   \\
    80648099\hline
    80658100\begin{cfa}
     
    80708105
    80718106        sout | 0 | fact;
    8072         for ( unsigned int i = 1; i <= 40; i += 1 ) {
     8107        for ( i; 40 ) {
    80738108                fact *= i;
    80748109                sout | i | fact;
     
    80928127\end{tabular}
    80938128\end{cquote}
    8094 
    8095 \begin{figure}
     8129\small
    80968130\begin{cfa}
    80978131Factorial Numbers
  • libcfa/src/concurrency/locks.hfa

    r665edf40 r73d0c54a  
    197197static inline $thread * unlock( fast_lock & this ) __attribute__((artificial));
    198198static inline $thread * unlock( fast_lock & this ) {
    199         $thread * thrd = active_thread();
    200         /* paranoid */ verify(thrd == this.owner);
     199        /* paranoid */ verify(active_thread() == this.owner);
    201200
    202201        // open 'owner' before unlocking anyone
  • libcfa/src/concurrency/ready_queue.cfa

    r665edf40 r73d0c54a  
    413413                        unsigned it2  = proc->rdq.itr + 1;
    414414                        unsigned idx1 = proc->rdq.id + (it1 % READYQ_SHARD_FACTOR);
    415                         unsigned idx2 = proc->rdq.id + (it1 % READYQ_SHARD_FACTOR);
     415                        unsigned idx2 = proc->rdq.id + (it2 % READYQ_SHARD_FACTOR);
    416416                        unsigned long long tsc1 = ts(lanes.data[idx1]);
    417417                        unsigned long long tsc2 = ts(lanes.data[idx2]);
    418418                        proc->rdq.cutoff = min(tsc1, tsc2);
    419                 }
    420                 else if(lanes.tscs[proc->rdq.target].tv < proc->rdq.cutoff) {
    421                         $thread * t = try_pop(cltr, proc->rdq.target __STATS(, __tls_stats()->ready.pop.help));
     419                        if(proc->rdq.cutoff == 0) proc->rdq.cutoff = -1ull;
     420                }
     421                else {
     422                        unsigned target = proc->rdq.target;
    422423                        proc->rdq.target = -1u;
    423                         if(t) return t;
     424                        if(lanes.tscs[target].tv < proc->rdq.cutoff) {
     425                                $thread * t = try_pop(cltr, target __STATS(, __tls_stats()->ready.pop.help));
     426                                if(t) return t;
     427                        }
    424428                }
    425429
  • libcfa/src/fstream.cfa

    r665edf40 r73d0c54a  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Mar  1 21:12:15 2021
    13 // Update Count     : 424
     12// Last Modified On : Tue Apr 20 19:04:46 2021
     13// Update Count     : 425
    1414//
    1515
     
    3131
    3232void ?{}( ofstream & os, void * file ) {
    33         os.$file = file;
    34         os.$sepDefault = true;
    35         os.$sepOnOff = false;
    36         os.$nlOnOff = true;
    37         os.$prt = false;
    38         os.$sawNL = false;
    39         os.$acquired = false;
    40         $sepSetCur( os, sepGet( os ) );
     33        os.file$ = file;
     34        os.sepDefault$ = true;
     35        os.sepOnOff$ = false;
     36        os.nlOnOff$ = true;
     37        os.prt$ = false;
     38        os.sawNL$ = false;
     39        os.acquired$ = false;
     40        sepSetCur$( os, sepGet( os ) );
    4141        sepSet( os, " " );
    4242        sepSetTuple( os, ", " );
     
    4444
    4545// private
    46 bool $sepPrt( ofstream & os ) { $setNL( os, false ); return os.$sepOnOff; }
    47 void $sepReset( ofstream & os ) { os.$sepOnOff = os.$sepDefault; }
    48 void $sepReset( ofstream & os, bool reset ) { os.$sepDefault = reset; os.$sepOnOff = os.$sepDefault; }
    49 const char * $sepGetCur( ofstream & os ) { return os.$sepCur; }
    50 void $sepSetCur( ofstream & os, const char sepCur[] ) { os.$sepCur = sepCur; }
    51 bool $getNL( ofstream & os ) { return os.$sawNL; }
    52 void $setNL( ofstream & os, bool state ) { os.$sawNL = state; }
    53 bool $getANL( ofstream & os ) { return os.$nlOnOff; }
    54 bool $getPrt( ofstream & os ) { return os.$prt; }
    55 void $setPrt( ofstream & os, bool state ) { os.$prt = state; }
     46bool sepPrt$( ofstream & os ) { setNL$( os, false ); return os.sepOnOff$; }
     47void sepReset$( ofstream & os ) { os.sepOnOff$ = os.sepDefault$; }
     48void sepReset$( ofstream & os, bool reset ) { os.sepDefault$ = reset; os.sepOnOff$ = os.sepDefault$; }
     49const char * sepGetCur$( ofstream & os ) { return os.sepCur$; }
     50void sepSetCur$( ofstream & os, const char sepCur[] ) { os.sepCur$ = sepCur; }
     51bool getNL$( ofstream & os ) { return os.sawNL$; }
     52void setNL$( ofstream & os, bool state ) { os.sawNL$ = state; }
     53bool getANL$( ofstream & os ) { return os.nlOnOff$; }
     54bool getPrt$( ofstream & os ) { return os.prt$; }
     55void setPrt$( ofstream & os, bool state ) { os.prt$ = state; }
    5656
    5757// public
    58 void ?{}( ofstream & os ) { os.$file = 0p; }
     58void ?{}( ofstream & os ) { os.file$ = 0p; }
    5959
    6060void ?{}( ofstream & os, const char name[], const char mode[] ) {
     
    7070} // ^?{}
    7171
    72 void sepOn( ofstream & os ) { os.$sepOnOff = ! $getNL( os ); }
    73 void sepOff( ofstream & os ) { os.$sepOnOff = false; }
     72void sepOn( ofstream & os ) { os.sepOnOff$ = ! getNL$( os ); }
     73void sepOff( ofstream & os ) { os.sepOnOff$ = false; }
    7474
    7575bool sepDisable( ofstream & os ) {
    76         bool temp = os.$sepDefault;
    77         os.$sepDefault = false;
    78         $sepReset( os );
     76        bool temp = os.sepDefault$;
     77        os.sepDefault$ = false;
     78        sepReset$( os );
    7979        return temp;
    8080} // sepDisable
    8181
    8282bool sepEnable( ofstream & os ) {
    83         bool temp = os.$sepDefault;
    84         os.$sepDefault = true;
    85         if ( os.$sepOnOff ) $sepReset( os );                            // start of line ?
     83        bool temp = os.sepDefault$;
     84        os.sepDefault$ = true;
     85        if ( os.sepOnOff$ ) sepReset$( os );                            // start of line ?
    8686        return temp;
    8787} // sepEnable
    8888
    89 void nlOn( ofstream & os ) { os.$nlOnOff = true; }
    90 void nlOff( ofstream & os ) { os.$nlOnOff = false; }
    91 
    92 const char * sepGet( ofstream & os ) { return os.$separator; }
     89void nlOn( ofstream & os ) { os.nlOnOff$ = true; }
     90void nlOff( ofstream & os ) { os.nlOnOff$ = false; }
     91
     92const char * sepGet( ofstream & os ) { return os.separator$; }
    9393void sepSet( ofstream & os, const char s[] ) {
    9494        assert( s );
    95         strncpy( os.$separator, s, sepSize - 1 );
    96         os.$separator[sepSize - 1] = '\0';
     95        strncpy( os.separator$, s, sepSize - 1 );
     96        os.separator$[sepSize - 1] = '\0';
    9797} // sepSet
    9898
    99 const char * sepGetTuple( ofstream & os ) { return os.$tupleSeparator; }
     99const char * sepGetTuple( ofstream & os ) { return os.tupleSeparator$; }
    100100void sepSetTuple( ofstream & os, const char s[] ) {
    101101        assert( s );
    102         strncpy( os.$tupleSeparator, s, sepSize - 1 );
    103         os.$tupleSeparator[sepSize - 1] = '\0';
     102        strncpy( os.tupleSeparator$, s, sepSize - 1 );
     103        os.tupleSeparator$[sepSize - 1] = '\0';
    104104} // sepSet
    105105
    106106void ends( ofstream & os ) {
    107         if ( $getANL( os ) ) nl( os );
    108         else $setPrt( os, false );                                                      // turn off
     107        if ( getANL$( os ) ) nl( os );
     108        else setPrt$( os, false );                                                      // turn off
    109109        if ( &os == &exit ) exit( EXIT_FAILURE );
    110110        if ( &os == &abort ) abort();
    111         if ( os.$acquired ) { os.$acquired = false; release( os ); }
     111        if ( os.acquired$ ) { os.acquired$ = false; release( os ); }
    112112} // ends
    113113
    114114int fail( ofstream & os ) {
    115         return os.$file == 0 || ferror( (FILE *)(os.$file) );
     115        return os.file$ == 0 || ferror( (FILE *)(os.file$) );
    116116} // fail
    117117
    118118int flush( ofstream & os ) {
    119         return fflush( (FILE *)(os.$file) );
     119        return fflush( (FILE *)(os.file$) );
    120120} // flush
    121121
     
    136136
    137137void close( ofstream & os ) {
    138   if ( (FILE *)(os.$file) == 0p ) return;
    139   if ( (FILE *)(os.$file) == (FILE *)stdout || (FILE *)(os.$file) == (FILE *)stderr ) return;
    140 
    141         if ( fclose( (FILE *)(os.$file) ) == EOF ) {
     138  if ( (FILE *)(os.file$) == 0p ) return;
     139  if ( (FILE *)(os.file$) == (FILE *)stdout || (FILE *)(os.file$) == (FILE *)stderr ) return;
     140
     141        if ( fclose( (FILE *)(os.file$) ) == EOF ) {
    142142                abort | IO_MSG "close output" | nl | strerror( errno );
    143143        } // if
    144         os.$file = 0p;
     144        os.file$ = 0p;
    145145} // close
    146146
     
    150150        } // if
    151151
    152         if ( fwrite( data, 1, size, (FILE *)(os.$file) ) != size ) {
     152        if ( fwrite( data, 1, size, (FILE *)(os.file$) ) != size ) {
    153153                abort | IO_MSG "write" | nl | strerror( errno );
    154154        } // if
     
    159159        va_list args;
    160160        va_start( args, format );
    161         int len = vfprintf( (FILE *)(os.$file), format, args );
     161        int len = vfprintf( (FILE *)(os.file$), format, args );
    162162        if ( len == EOF ) {
    163                 if ( ferror( (FILE *)(os.$file) ) ) {
     163                if ( ferror( (FILE *)(os.file$) ) ) {
    164164                        abort | IO_MSG "invalid write";
    165165                } // if
     
    167167        va_end( args );
    168168
    169         $setPrt( os, true );                                                            // called in output cascade
    170         $sepReset( os );                                                                        // reset separator
     169        setPrt$( os, true );                                                            // called in output cascade
     170        sepReset$( os );                                                                        // reset separator
    171171        return len;
    172172} // fmt
    173173
    174174inline void acquire( ofstream & os ) {
    175         lock( os.$lock );
    176         if ( ! os.$acquired ) os.$acquired = true;
    177         else unlock( os.$lock );
     175        lock( os.lock$ );
     176        if ( ! os.acquired$ ) os.acquired$ = true;
     177        else unlock( os.lock$ );
    178178} // acquire
    179179
    180180inline void release( ofstream & os ) {
    181         unlock( os.$lock );
     181        unlock( os.lock$ );
    182182} // release
    183183
    184 void ?{}( osacquire & acq, ofstream & os ) { &acq.os = &os; lock( os.$lock ); }
     184void ?{}( osacquire & acq, ofstream & os ) { &acq.os = &os; lock( os.lock$ ); }
    185185void ^?{}( osacquire & acq ) { release( acq.os ); }
    186186
     
    204204// private
    205205void ?{}( ifstream & is, void * file ) {
    206         is.$file = file;
    207         is.$nlOnOff = false;
    208         is.$acquired = false;
     206        is.file$ = file;
     207        is.nlOnOff$ = false;
     208        is.acquired$ = false;
    209209} // ?{}
    210210
    211211// public
    212 void ?{}( ifstream & is ) { is.$file = 0p; }
     212void ?{}( ifstream & is ) { is.file$ = 0p; }
    213213
    214214void ?{}( ifstream & is, const char name[], const char mode[] ) {
     
    224224} // ^?{}
    225225
    226 void nlOn( ifstream & os ) { os.$nlOnOff = true; }
    227 void nlOff( ifstream & os ) { os.$nlOnOff = false; }
    228 bool getANL( ifstream & os ) { return os.$nlOnOff; }
     226void nlOn( ifstream & os ) { os.nlOnOff$ = true; }
     227void nlOff( ifstream & os ) { os.nlOnOff$ = false; }
     228bool getANL( ifstream & os ) { return os.nlOnOff$; }
    229229
    230230int fail( ifstream & is ) {
    231         return is.$file == 0p || ferror( (FILE *)(is.$file) );
     231        return is.file$ == 0p || ferror( (FILE *)(is.file$) );
    232232} // fail
    233233
    234234void ends( ifstream & is ) {
    235         if ( is.$acquired ) { is.$acquired = false; release( is ); }
     235        if ( is.acquired$ ) { is.acquired$ = false; release( is ); }
    236236} // ends
    237237
    238238int eof( ifstream & is ) {
    239         return feof( (FILE *)(is.$file) );
     239        return feof( (FILE *)(is.file$) );
    240240} // eof
    241241
     
    248248        } // if
    249249        #endif // __CFA_DEBUG__
    250         is.$file = file;
     250        is.file$ = file;
    251251} // open
    252252
     
    256256
    257257void close( ifstream & is ) {
    258   if ( (FILE *)(is.$file) == 0p ) return;
    259   if ( (FILE *)(is.$file) == (FILE *)stdin ) return;
    260 
    261         if ( fclose( (FILE *)(is.$file) ) == EOF ) {
     258  if ( (FILE *)(is.file$) == 0p ) return;
     259  if ( (FILE *)(is.file$) == (FILE *)stdin ) return;
     260
     261        if ( fclose( (FILE *)(is.file$) ) == EOF ) {
    262262                abort | IO_MSG "close input" | nl | strerror( errno );
    263263        } // if
    264         is.$file = 0p;
     264        is.file$ = 0p;
    265265} // close
    266266
     
    270270        } // if
    271271
    272         if ( fread( data, size, 1, (FILE *)(is.$file) ) == 0 ) {
     272        if ( fread( data, size, 1, (FILE *)(is.file$) ) == 0 ) {
    273273                abort | IO_MSG "read" | nl | strerror( errno );
    274274        } // if
     
    281281        } // if
    282282
    283         if ( ungetc( c, (FILE *)(is.$file) ) == EOF ) {
     283        if ( ungetc( c, (FILE *)(is.file$) ) == EOF ) {
    284284                abort | IO_MSG "ungetc" | nl | strerror( errno );
    285285        } // if
     
    291291
    292292        va_start( args, format );
    293         int len = vfscanf( (FILE *)(is.$file), format, args );
     293        int len = vfscanf( (FILE *)(is.file$), format, args );
    294294        if ( len == EOF ) {
    295                 if ( ferror( (FILE *)(is.$file) ) ) {
     295                if ( ferror( (FILE *)(is.file$) ) ) {
    296296                        abort | IO_MSG "invalid read";
    297297                } // if
     
    302302
    303303inline void acquire( ifstream & is ) {
    304         lock( is.$lock );
    305         if ( ! is.$acquired ) is.$acquired = true;
    306         else unlock( is.$lock );
     304        lock( is.lock$ );
     305        if ( ! is.acquired$ ) is.acquired$ = true;
     306        else unlock( is.lock$ );
    307307} // acquire
    308308
    309309inline void release( ifstream & is ) {
    310         unlock( is.$lock );
     310        unlock( is.lock$ );
    311311} // release
    312312
    313 void ?{}( isacquire & acq, ifstream & is ) { &acq.is = &is; lock( is.$lock ); }
     313void ?{}( isacquire & acq, ifstream & is ) { &acq.is = &is; lock( is.lock$ ); }
    314314void ^?{}( isacquire & acq ) { release( acq.is ); }
    315315
  • libcfa/src/fstream.hfa

    r665edf40 r73d0c54a  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Mon Mar  1 22:45:08 2021
    13 // Update Count     : 217
     12// Last Modified On : Tue Apr 20 19:04:12 2021
     13// Update Count     : 218
    1414//
    1515
     
    2626enum { sepSize = 16 };
    2727struct ofstream {
    28         void * $file;
    29         bool $sepDefault;
    30         bool $sepOnOff;
    31         bool $nlOnOff;
    32         bool $prt;                                                                                      // print text
    33         bool $sawNL;
    34         const char * $sepCur;
    35         char $separator[sepSize];
    36         char $tupleSeparator[sepSize];
    37         multiple_acquisition_lock $lock;
    38         bool $acquired;
     28        void * file$;
     29        bool sepDefault$;
     30        bool sepOnOff$;
     31        bool nlOnOff$;
     32        bool prt$;                                                                                      // print text
     33        bool sawNL$;
     34        const char * sepCur$;
     35        char separator$[sepSize];
     36        char tupleSeparator$[sepSize];
     37        multiple_acquisition_lock lock$;
     38        bool acquired$;
    3939}; // ofstream
    4040
    4141// private
    42 bool $sepPrt( ofstream & );
    43 void $sepReset( ofstream & );
    44 void $sepReset( ofstream &, bool );
    45 const char * $sepGetCur( ofstream & );
    46 void $sepSetCur( ofstream &, const char [] );
    47 bool $getNL( ofstream & );
    48 void $setNL( ofstream &, bool );
    49 bool $getANL( ofstream & );
    50 bool $getPrt( ofstream & );
    51 void $setPrt( ofstream &, bool );
     42bool sepPrt$( ofstream & );
     43void sepReset$( ofstream & );
     44void sepReset$( ofstream &, bool );
     45const char * sepGetCur$( ofstream & );
     46void sepSetCur$( ofstream &, const char [] );
     47bool getNL$( ofstream & );
     48void setNL$( ofstream &, bool );
     49bool getANL$( ofstream & );
     50bool getPrt$( ofstream & );
     51void setPrt$( ofstream &, bool );
    5252
    5353// public
     
    9494
    9595struct ifstream {
    96         void * $file;
    97         bool $nlOnOff;
    98         multiple_acquisition_lock $lock;
    99         bool $acquired;
     96        void * file$;
     97        bool nlOnOff$;
     98        multiple_acquisition_lock lock$;
     99        bool acquired$;
    100100}; // ifstream
    101101
  • libcfa/src/gmp.hfa

    r665edf40 r73d0c54a  
    1010// Created On       : Tue Apr 19 08:43:43 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sun Feb  9 09:56:54 2020
    13 // Update Count     : 31
     12// Last Modified On : Tue Apr 20 20:59:21 2021
     13// Update Count     : 32
    1414//
    1515
     
    263263        forall( ostype & | ostream( ostype ) ) {
    264264                ostype & ?|?( ostype & os, Int mp ) {
    265                         if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     265                        if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    266266                        gmp_printf( "%Zd", mp.mpz );
    267267                        sepOn( os );
  • libcfa/src/heap.cfa

    r665edf40 r73d0c54a  
    1010// Created On       : Tue Dec 19 21:58:35 2017
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Sun Mar 14 10:39:24 2021
    13 // Update Count     : 1032
     12// Last Modified On : Tue Apr 20 21:20:48 2021
     13// Update Count     : 1033
    1414//
    1515
     
    11281128
    11291129        // Set the alignment for an the allocation and return previous alignment or 0 if no alignment.
    1130         size_t $malloc_alignment_set( void * addr, size_t alignment ) {
     1130        size_t malloc_alignment_set$( void * addr, size_t alignment ) {
    11311131          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
    11321132                size_t ret;
     
    11391139                } // if
    11401140                return ret;
    1141         } // $malloc_alignment_set
     1141        } // malloc_alignment_set$
    11421142
    11431143
     
    11531153
    11541154        // Set allocation is zero filled and return previous zero filled.
    1155         bool $malloc_zero_fill_set( void * addr ) {
     1155        bool malloc_zero_fill_set$( void * addr ) {
    11561156          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
    11571157                HeapManager.Storage.Header * header = headerAddr( addr );
     
    11621162                header->kind.real.blockSize |= 2;                               // mark as zero filled
    11631163                return ret;
    1164         } // $malloc_zero_fill_set
     1164        } // malloc_zero_fill_set$
    11651165
    11661166
     
    11761176
    11771177        // Set allocation size and return previous size.
    1178         size_t $malloc_size_set( void * addr, size_t size ) {
     1178        size_t malloc_size_set$( void * addr, size_t size ) {
    11791179          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
    11801180                HeapManager.Storage.Header * header = headerAddr( addr );
     
    11851185                header->kind.real.size = size;
    11861186                return ret;
    1187         } // $malloc_size_set
     1187        } // malloc_size_set$
    11881188
    11891189
  • libcfa/src/iostream.cfa

    r665edf40 r73d0c54a  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue Apr 13 13:05:24 2021
    13 // Update Count     : 1324
     12// Last Modified On : Tue Apr 20 19:09:41 2021
     13// Update Count     : 1325
    1414//
    1515
     
    3838forall( ostype & | ostream( ostype ) ) {
    3939        ostype & ?|?( ostype & os, bool b ) {
    40                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     40                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    4141                fmt( os, "%s", b ? "true" : "false" );
    4242                return os;
     
    4848        ostype & ?|?( ostype & os, char c ) {
    4949                fmt( os, "%c", c );
    50                 if ( c == '\n' ) $setNL( os, true );
     50                if ( c == '\n' ) setNL$( os, true );
    5151                return sepOff( os );
    5252        } // ?|?
     
    5656
    5757        ostype & ?|?( ostype & os, signed char sc ) {
    58                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     58                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    5959                fmt( os, "%hhd", sc );
    6060                return os;
     
    6565
    6666        ostype & ?|?( ostype & os, unsigned char usc ) {
    67                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     67                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    6868                fmt( os, "%hhu", usc );
    6969                return os;
     
    7474
    7575        ostype & ?|?( ostype & os, short int si ) {
    76                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     76                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    7777                fmt( os, "%hd", si );
    7878                return os;
     
    8383
    8484        ostype & ?|?( ostype & os, unsigned short int usi ) {
    85                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     85                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    8686                fmt( os, "%hu", usi );
    8787                return os;
     
    9292
    9393        ostype & ?|?( ostype & os, int i ) {
    94                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     94                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    9595                fmt( os, "%d", i );
    9696                return os;
     
    101101
    102102        ostype & ?|?( ostype & os, unsigned int ui ) {
    103                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     103                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    104104                fmt( os, "%u", ui );
    105105                return os;
     
    110110
    111111        ostype & ?|?( ostype & os, long int li ) {
    112                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     112                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    113113                fmt( os, "%ld", li );
    114114                return os;
     
    119119
    120120        ostype & ?|?( ostype & os, unsigned long int uli ) {
    121                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     121                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    122122                fmt( os, "%lu", uli );
    123123                return os;
     
    128128
    129129        ostype & ?|?( ostype & os, long long int lli ) {
    130                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     130                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    131131                fmt( os, "%lld", lli );
    132132                return os;
     
    137137
    138138        ostype & ?|?( ostype & os, unsigned long long int ulli ) {
    139                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     139                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    140140                fmt( os, "%llu", ulli );
    141141                return os;
     
    171171
    172172        ostype & ?|?( ostype & os, int128 llli ) {
    173                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     173                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    174174                base10_128( os, llli );
    175175                return os;
     
    180180
    181181        ostype & ?|?( ostype & os, unsigned int128 ullli ) {
    182                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     182                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    183183                base10_128( os, ullli );
    184184                return os;
     
    204204
    205205        ostype & ?|?( ostype & os, float f ) {
    206                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     206                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    207207                PrintWithDP( os, "%g", f );
    208208                return os;
     
    213213
    214214        ostype & ?|?( ostype & os, double d ) {
    215                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     215                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    216216                PrintWithDP( os, "%.*lg", d, DBL_DIG );
    217217                return os;
     
    222222
    223223        ostype & ?|?( ostype & os, long double ld ) {
    224                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     224                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    225225                PrintWithDP( os, "%.*Lg", ld, LDBL_DIG );
    226226                return os;
     
    231231
    232232        ostype & ?|?( ostype & os, float _Complex fc ) {
    233                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     233                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    234234//              os | crealf( fc ) | nonl;
    235235                PrintWithDP( os, "%g", crealf( fc ) );
     
    243243
    244244        ostype & ?|?( ostype & os, double _Complex dc ) {
    245                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     245                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    246246//              os | creal( dc ) | nonl;
    247247                PrintWithDP( os, "%.*lg", creal( dc ), DBL_DIG );
     
    255255
    256256        ostype & ?|?( ostype & os, long double _Complex ldc ) {
    257                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     257                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    258258//              os | creall( ldc ) || nonl;
    259259                PrintWithDP( os, "%.*Lg", creall( ldc ), LDBL_DIG );
     
    286286                // first character IS NOT spacing or closing punctuation => add left separator
    287287                unsigned char ch = s[0];                                                // must make unsigned
    288                 if ( $sepPrt( os ) && mask[ ch ] != Close && mask[ ch ] != OpenClose ) {
    289                         fmt( os, "%s", $sepGetCur( os ) );
     288                if ( sepPrt$( os ) && mask[ ch ] != Close && mask[ ch ] != OpenClose ) {
     289                        fmt( os, "%s", sepGetCur$( os ) );
    290290                } // if
    291291
    292292                // if string starts line, must reset to determine open state because separator is off
    293                 $sepReset( os );                                                                // reset separator
     293                sepReset$( os );                                                                // reset separator
    294294
    295295                // last character IS spacing or opening punctuation => turn off separator for next item
    296296                size_t len = strlen( s );
    297297                ch = s[len - 1];                                                                // must make unsigned
    298                 if ( $sepPrt( os ) && mask[ ch ] != Open && mask[ ch ] != OpenClose ) {
     298                if ( sepPrt$( os ) && mask[ ch ] != Open && mask[ ch ] != OpenClose ) {
    299299                        sepOn( os );
    300300                } else {
    301301                        sepOff( os );
    302302                } // if
    303                 if ( ch == '\n' ) $setNL( os, true );                   // check *AFTER* $sepPrt call above as it resets NL flag
     303                if ( ch == '\n' ) setNL$( os, true );                   // check *AFTER* sepPrt$ call above as it resets NL flag
    304304                return write( os, s, len );
    305305        } // ?|?
     
    309309
    310310//      ostype & ?|?( ostype & os, const char16_t * s ) {
    311 //              if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     311//              if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    312312//              fmt( os, "%ls", s );
    313313//              return os;
     
    316316// #if ! ( __ARM_ARCH_ISA_ARM == 1 && __ARM_32BIT_STATE == 1 ) // char32_t == wchar_t => ambiguous
    317317//      ostype & ?|?( ostype & os, const char32_t * s ) {
    318 //              if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     318//              if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    319319//              fmt( os, "%ls", s );
    320320//              return os;
     
    323323
    324324//      ostype & ?|?( ostype & os, const wchar_t * s ) {
    325 //              if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     325//              if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    326326//              fmt( os, "%ls", s );
    327327//              return os;
     
    329329
    330330        ostype & ?|?( ostype & os, const void * p ) {
    331                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     331                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    332332                fmt( os, "%p", p );
    333333                return os;
     
    343343        void ?|?( ostype & os, ostype & (* manip)( ostype & ) ) {
    344344                manip( os );
    345                 if ( $getPrt( os ) ) ends( os );                                // something printed ?
    346                 $setPrt( os, false );                                                   // turn off
     345                if ( getPrt$( os ) ) ends( os );                                // something printed ?
     346                setPrt$( os, false );                                                   // turn off
    347347        } // ?|?
    348348
     
    357357        ostype & nl( ostype & os ) {
    358358                (ostype &)(os | '\n');
    359                 $setPrt( os, false );                                                   // turn off
    360                 $setNL( os, true );
     359                setPrt$( os, false );                                                   // turn off
     360                setNL$( os, true );
    361361                flush( os );
    362362                return sepOff( os );                                                    // prepare for next line
     
    364364
    365365        ostype & nonl( ostype & os ) {
    366                 $setPrt( os, false );                                                   // turn off
     366                setPrt$( os, false );                                                   // turn off
    367367                return os;
    368368        } // nonl
     
    408408        ostype & ?|?( ostype & os, T arg, Params rest ) {
    409409                (ostype &)(os | arg);                                                   // print first argument
    410                 $sepSetCur( os, sepGetTuple( os ) );                    // switch to tuple separator
     410                sepSetCur$( os, sepGetTuple( os ) );                    // switch to tuple separator
    411411                (ostype &)(os | rest);                                                  // print remaining arguments
    412                 $sepSetCur( os, sepGet( os ) );                                 // switch to regular separator
     412                sepSetCur$( os, sepGet( os ) );                                 // switch to regular separator
    413413                return os;
    414414        } // ?|?
     
    416416                // (ostype &)(?|?( os, arg, rest )); ends( os );
    417417                (ostype &)(os | arg);                                                   // print first argument
    418                 $sepSetCur( os, sepGetTuple( os ) );                    // switch to tuple separator
     418                sepSetCur$( os, sepGetTuple( os ) );                    // switch to tuple separator
    419419                (ostype &)(os | rest);                                                  // print remaining arguments
    420                 $sepSetCur( os, sepGet( os ) );                                 // switch to regular separator
     420                sepSetCur$( os, sepGet( os ) );                                 // switch to regular separator
    421421                ends( os );
    422422        } // ?|?
     
    447447forall( ostype & | ostream( ostype ) ) { \
    448448        ostype & ?|?( ostype & os, _Ostream_Manip(T) f ) { \
    449                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) ); \
     449                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) ); \
    450450\
    451451                if ( f.base == 'b' || f.base == 'B' ) {                 /* bespoke binary format */ \
     
    691691                int bufbeg = 0, i, len; \
    692692\
    693                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) ); \
     693                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) ); \
    694694                char fmtstr[sizeof(DFMTP) + 8];                                 /* sizeof includes '\0' */ \
    695695                if ( ! f.flags.pc ) memcpy( &fmtstr, DFMTNP, sizeof(DFMTNP) ); \
     
    734734                } // if
    735735
    736                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     736                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    737737
    738738                #define CFMTNP "% * "
     
    772772                } // if
    773773
    774                 if ( $sepPrt( os ) ) fmt( os, "%s", $sepGetCur( os ) );
     774                if ( sepPrt$( os ) ) fmt( os, "%s", sepGetCur$( os ) );
    775775
    776776                #define SFMTNP "% * "
  • libcfa/src/iostream.hfa

    r665edf40 r73d0c54a  
    1010// Created On       : Wed May 27 17:56:53 2015
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue Apr 13 13:05:11 2021
    13 // Update Count     : 384
     12// Last Modified On : Tue Apr 20 19:09:44 2021
     13// Update Count     : 385
    1414//
    1515
     
    2424trait ostream( ostype & ) {
    2525        // private
    26         bool $sepPrt( ostype & );                                                       // get separator state (on/off)
    27         void $sepReset( ostype & );                                                     // set separator state to default state
    28         void $sepReset( ostype &, bool );                                       // set separator and default state
    29         const char * $sepGetCur( ostype & );                            // get current separator string
    30         void $sepSetCur( ostype &, const char [] );                     // set current separator string
    31         bool $getNL( ostype & );                                                        // check newline
    32         void $setNL( ostype &, bool );                                          // saw newline
    33         bool $getANL( ostype & );                                                       // get auto newline (on/off)
    34         bool $getPrt( ostype & );                                                       // get fmt called in output cascade
    35         void $setPrt( ostype &, bool );                                         // set fmt called in output cascade
     26        bool sepPrt$( ostype & );                                                       // get separator state (on/off)
     27        void sepReset$( ostype & );                                                     // set separator state to default state
     28        void sepReset$( ostype &, bool );                                       // set separator and default state
     29        const char * sepGetCur$( ostype & );                            // get current separator string
     30        void sepSetCur$( ostype &, const char [] );                     // set current separator string
     31        bool getNL$( ostype & );                                                        // check newline
     32        void setNL$( ostype &, bool );                                          // saw newline
     33        bool getANL$( ostype & );                                                       // get auto newline (on/off)
     34        bool getPrt$( ostype & );                                                       // get fmt called in output cascade
     35        void setPrt$( ostype &, bool );                                         // set fmt called in output cascade
    3636        // public
    3737        void sepOn( ostype & );                                                         // turn separator state on
  • libcfa/src/stdlib.hfa

    r665edf40 r73d0c54a  
    1010// Created On       : Thu Jan 28 17:12:35 2016
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Thu Jan 21 22:02:13 2021
    13 // Update Count     : 574
     12// Last Modified On : Tue Apr 20 21:20:03 2021
     13// Update Count     : 575
    1414//
    1515
     
    4444
    4545// Macro because of returns
    46 #define $ARRAY_ALLOC( allocation, alignment, dim ) \
     46#define ARRAY_ALLOC$( allocation, alignment, dim ) \
    4747        if ( _Alignof(T) <= libAlign() ) return (T *)(void *)allocation( dim, (size_t)sizeof(T) ); /* C allocation */ \
    4848        else return (T *)alignment( _Alignof(T), dim, sizeof(T) )
     
    5757
    5858        T * aalloc( size_t dim ) {
    59                 $ARRAY_ALLOC( aalloc, amemalign, dim );
     59                ARRAY_ALLOC$( aalloc, amemalign, dim );
    6060        } // aalloc
    6161
    6262        T * calloc( size_t dim ) {
    63                 $ARRAY_ALLOC( calloc, cmemalign, dim );
     63                ARRAY_ALLOC$( calloc, cmemalign, dim );
    6464        } // calloc
    6565
     
    119119                S_fill(T) ?`fill( T    a[], size_t nmemb )      { S_fill(T) ret = {'a', nmemb}; ret.fill.a = a; return ret; }
    120120
    121         3. Replace the $alloc_internal function which is outside ttype forall-block with following function:
    122                 T * $alloc_internal( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill) {
     121        3. Replace the alloc_internal$ function which is outside ttype forall-block with following function:
     122                T * alloc_internal$( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill) {
    123123                        T * ptr = NULL;
    124124                        size_t size = sizeof(T);
     
    145145
    146146                        return ptr;
    147                 } // $alloc_internal
     147                } // alloc_internal$
    148148*/
    149149
     
    175175        S_realloc(T)    ?`realloc ( T * a )                             { return (S_realloc(T)){a}; }
    176176
    177         T * $alloc_internal( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill ) {
     177        T * alloc_internal$( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill ) {
    178178                T * ptr = NULL;
    179179                size_t size = sizeof(T);
     
    206206
    207207                return ptr;
    208         } // $alloc_internal
    209 
    210         forall( TT... | { T * $alloc_internal( void *, T *, size_t, size_t, S_fill(T), TT ); } ) {
    211 
    212                 T * $alloc_internal( void *       , T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill, T_resize Resize, TT rest) {
    213                 return $alloc_internal( Resize, (T*)0p, Align, Dim, Fill, rest);
    214                 }
    215 
    216                 T * $alloc_internal( void * Resize, T *        , size_t Align, size_t Dim, S_fill(T) Fill, S_realloc(T) Realloc, TT rest) {
    217                 return $alloc_internal( (void*)0p, Realloc, Align, Dim, Fill, rest);
    218                 }
    219 
    220                 T * $alloc_internal( void * Resize, T * Realloc, size_t      , size_t Dim, S_fill(T) Fill, T_align Align, TT rest) {
    221                 return $alloc_internal( Resize, Realloc, Align, Dim, Fill, rest);
    222                 }
    223 
    224                 T * $alloc_internal( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T)     , S_fill(T) Fill, TT rest) {
    225                 return $alloc_internal( Resize, Realloc, Align, Dim, Fill, rest);
     208        } // alloc_internal$
     209
     210        forall( TT... | { T * alloc_internal$( void *, T *, size_t, size_t, S_fill(T), TT ); } ) {
     211
     212                T * alloc_internal$( void *       , T * Realloc, size_t Align, size_t Dim, S_fill(T) Fill, T_resize Resize, TT rest) {
     213                return alloc_internal$( Resize, (T*)0p, Align, Dim, Fill, rest);
     214                }
     215
     216                T * alloc_internal$( void * Resize, T *        , size_t Align, size_t Dim, S_fill(T) Fill, S_realloc(T) Realloc, TT rest) {
     217                return alloc_internal$( (void*)0p, Realloc, Align, Dim, Fill, rest);
     218                }
     219
     220                T * alloc_internal$( void * Resize, T * Realloc, size_t      , size_t Dim, S_fill(T) Fill, T_align Align, TT rest) {
     221                return alloc_internal$( Resize, Realloc, Align, Dim, Fill, rest);
     222                }
     223
     224                T * alloc_internal$( void * Resize, T * Realloc, size_t Align, size_t Dim, S_fill(T)     , S_fill(T) Fill, TT rest) {
     225                return alloc_internal$( Resize, Realloc, Align, Dim, Fill, rest);
    226226                }
    227227
    228228            T * alloc( TT all ) {
    229                 return $alloc_internal( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), (size_t)1, (S_fill(T)){'0'}, all);
     229                return alloc_internal$( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), (size_t)1, (S_fill(T)){'0'}, all);
    230230            }
    231231
    232232            T * alloc( size_t dim, TT all ) {
    233                 return $alloc_internal( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), dim, (S_fill(T)){'0'}, all);
     233                return alloc_internal$( (void*)0p, (T*)0p, (_Alignof(T) > libAlign() ? _Alignof(T) : libAlign()), dim, (S_fill(T)){'0'}, all);
    234234            }
    235235
  • libcfa/src/time.hfa

    r665edf40 r73d0c54a  
    1010// Created On       : Wed Mar 14 23:18:57 2018
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Wed Apr 14 09:30:30 2021
    13 // Update Count     : 664
     12// Last Modified On : Wed Apr 21 06:32:31 2021
     13// Update Count     : 667
    1414//
    1515
     
    2828
    2929static inline {
     30        void ?{}( Duration & dur, timeval t ) with( dur ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * 1000; }
     31        void ?{}( Duration & dur, timespec t ) with( dur ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec; }
     32
    3033        Duration ?=?( Duration & dur, __attribute__((unused)) zero_t ) { return dur{ 0 }; }
    31 
    32         void ?{}( Duration & dur, timeval t ) with( dur ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * 1000; }
    3334        Duration ?=?( Duration & dur, timeval t ) with( dur ) {
    3435                tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * (TIMEGRAN / 1_000_000LL);
    3536                return dur;
    3637        } // ?=?
    37 
    38         void ?{}( Duration & dur, timespec t ) with( dur ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec; }
    3938        Duration ?=?( Duration & dur, timespec t ) with( dur ) {
    4039                tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec;
     
    6160        Duration ?%?( Duration lhs, Duration rhs ) { return (Duration)@{ lhs.tn % rhs.tn }; }
    6261        Duration ?%=?( Duration & lhs, Duration rhs ) { lhs = lhs % rhs; return lhs; }
     62
     63        bool ?==?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn == 0; }
     64        bool ?!=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn != 0; }
     65        bool ?<? ( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn <  0; }
     66        bool ?<=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn <= 0; }
     67        bool ?>? ( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn >  0; }
     68        bool ?>=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn >= 0; }
    6369
    6470        bool ?==?( Duration lhs, Duration rhs ) { return lhs.tn == rhs.tn; }
     
    6874        bool ?>? ( Duration lhs, Duration rhs ) { return lhs.tn >  rhs.tn; }
    6975        bool ?>=?( Duration lhs, Duration rhs ) { return lhs.tn >= rhs.tn; }
    70 
    71         bool ?==?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn == 0; }
    72         bool ?!=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn != 0; }
    73         bool ?<? ( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn <  0; }
    74         bool ?<=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn <= 0; }
    75         bool ?>? ( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn >  0; }
    76         bool ?>=?( Duration lhs, __attribute__((unused)) zero_t ) { return lhs.tn >= 0; }
    7776
    7877        Duration abs( Duration rhs ) { return rhs.tn >= 0 ? rhs : -rhs; }
     
    164163void ?{}( Time & time, int year, int month = 1, int day = 1, int hour = 0, int min = 0, int sec = 0, int64_t nsec = 0 );
    165164static inline {
     165        void ?{}( Time & time, timeval t ) with( time ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * 1000; }
     166        void ?{}( Time & time, timespec t ) with( time ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec; }
     167
    166168        Time ?=?( Time & time, __attribute__((unused)) zero_t ) { return time{ 0 }; }
    167 
    168         void ?{}( Time & time, timeval t ) with( time ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * 1000; }
    169169        Time ?=?( Time & time, timeval t ) with( time ) {
    170170                tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_usec * (TIMEGRAN / 1_000_000LL);
    171171                return time;
    172172        } // ?=?
    173 
    174         void ?{}( Time & time, timespec t ) with( time ) { tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec; }
    175173        Time ?=?( Time & time, timespec t ) with( time ) {
    176174                tn = (int64_t)t.tv_sec * TIMEGRAN + t.tv_nsec;
Note: See TracChangeset for help on using the changeset viewer.