Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/papers/general/Paper.tex

    r6dba9f99 rab3251e  
    1313\usepackage{pslatex}                                            % reduce size of san serif font
    1414\usepackage[plainpages=false,pdfpagelabels,pdfpagemode=UseNone,pagebackref=true,breaklinks=true,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}
    15 \urlstyle{sf}
    16 \usepackage{breakurl}
    1715
    1816\setlength{\textheight}{9in}
     
    5856\setlength{\parindentlnth}{\parindent}
    5957
    60 \newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{\lst@basicstyle{#1}}}}
    6158\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
    6259\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
     
    232229All of the features discussed in this paper are working, unless a feature states it is a future feature for completion.
    233230
    234 Finally, it is impossible to describe a programming language without usages before definitions.
    235 Therefore, syntax and semantics appear before explanations;
    236 hence, patience is necessary until details are presented.
    237 
    238231
    239232\section{Polymorphic Functions}
     
    268261\end{cfa}
    269262\CFA maximizes the ability to reuse names to aggressively address the naming problem.
    270 In some cases, hundreds of names can be reduced to tens, resulting in a significant cognitive reduction.
     263In some cases, hundreds of names can be reduced to tens, resulting in a significant cognitive reduction for a programmer.
    271264In the above, the name @max@ has a consistent meaning, and a programmer only needs to remember the single concept: maximum.
    272265To prevent significant ambiguities, \CFA uses the return type in selecting overloads, \eg in the assignment to @m@, the compiler use @m@'s type to unambiguously select the most appropriate call to function @max@ (as does Ada).
    273266As is shown later, there are a number of situations where \CFA takes advantage of available type information to disambiguate, where other programming languages generate ambiguities.
    274267
    275 \Celeven added @_Generic@ expressions, which is used in preprocessor macros to provide a form of ad-hoc polymorphism;
    276 however, this polymorphism is both functionally and ergonomically inferior to \CFA name overloading.
    277 The macro wrapping the generic expression imposes some limitations;
    278 \eg, it cannot implement the example above, because the variables @max@ are ambiguous with the functions @max@.
    279 Ergonomic limitations of @_Generic@ include the necessity to put a fixed list of supported types in a single place and manually dispatch to appropriate overloads, as well as possible namespace pollution from the dispatch functions, which must all have distinct names.
    280 For backwards compatibility, \CFA supports @_Generic@ expressions, but it is an unnecessary mechanism. \TODO{actually implement that}
     268\Celeven added @_Generic@ expressions, which can be used in preprocessor macros to provide a form of ad-hoc polymorphism; however, this polymorphism is both functionally and ergonomically inferior to \CFA name overloading.
     269The macro wrapping the generic expression imposes some limitations; as an example, it could not implement the example above, because the variables @max@ would collide with the functions @max@.
     270Ergonomic limitations of @_Generic@ include the necessity to put a fixed list of supported types in a single place and manually dispatch to appropriate overloads, as well as possible namespace pollution from the functions dispatched to, which must all have distinct names.
     271Though name-overloading removes a major use-case for @_Generic@ expressions, \CFA implements @_Generic@ for backwards-compatibility purposes. \TODO{actually implement that}
    281272
    282273% http://fanf.livejournal.com/144696.html
     
    293284int forty_two = identity( 42 );                         $\C{// T is bound to int, forty\_two == 42}$
    294285\end{cfa}
    295 This @identity@ function can be applied to any complete \newterm{object type} (or @otype@).
     286The @identity@ function above can be applied to any complete \newterm{object type} (or @otype@).
    296287The type variable @T@ is transformed into a set of additional implicit parameters encoding sufficient information about @T@ to create and return a variable of that type.
    297288The \CFA implementation passes the size and alignment of the type represented by an @otype@ parameter, as well as an assignment operator, constructor, copy constructor and destructor.
    298289If this extra information is not needed, \eg for a pointer, the type parameter can be declared as a \newterm{data type} (or @dtype@).
    299290
    300 In \CFA, the polymorphic runtime-cost is spread over each polymorphic call, because more arguments are passed to polymorphic functions;
     291In \CFA, the polymorphism runtime-cost is spread over each polymorphic call, due to passing more arguments to polymorphic functions;
    301292the experiments in Section~\ref{sec:eval} show this overhead is similar to \CC virtual-function calls.
    302293A design advantage is that, unlike \CC template-functions, \CFA polymorphic-functions are compatible with C \emph{separate compilation}, preventing compilation and code bloat.
     
    310301which works for any type @T@ with a matching addition operator.
    311302The polymorphism is achieved by creating a wrapper function for calling @+@ with @T@ bound to @double@, then passing this function to the first call of @twice@.
    312 There is now the option of using the same @twice@ and converting the result to @int@ on assignment, or creating another @twice@ with type parameter @T@ bound to @int@ because \CFA uses the return type~\cite{Cormack81,Baker82,Ada} in its type analysis.
     303There is now the option of using the same @twice@ and converting the result to @int@ on assignment, or creating another @twice@ with type parameter @T@ bound to @int@ because \CFA uses the return type~\cite{Cormack81,Baker82,Ada}, in its type analysis.
    313304The first approach has a late conversion from @double@ to @int@ on the final assignment, while the second has an eager conversion to @int@.
    314305\CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach, which corresponds with C-programmer intuition.
     
    319310\begin{cfa}
    320311void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
    321                                          int (* compar)( const void *, const void * ));
    322 int comp( const void * t1, const void * t2 ) {
    323          return *(double *)t1 < *(double *)t2 ? -1 : *(double *)t2 < *(double *)t1 ? 1 : 0;
    324 }
     312                                int (* compar)( const void *, const void * ));
     313
     314int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 :
     315                                *(double *)t2 < *(double *)t1 ? 1 : 0; }
     316
    325317double key = 5.0, vals[10] = { /* 10 sorted float values */ };
    326318double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp );      $\C{// search sorted array}$
     
    330322forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) {
    331323        int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ }
    332         return (T *)bsearch( &key, arr, size, sizeof(T), comp );
    333 }
     324        return (T *)bsearch( &key, arr, size, sizeof(T), comp ); }
     325
    334326forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) {
    335327        T * result = bsearch( key, arr, size ); $\C{// call first version}$
    336         return result ? result - arr : size;    $\C{// pointer subtraction includes sizeof(T)}$
    337 }
     328        return result ? result - arr : size; }  $\C{// pointer subtraction includes sizeof(T)}$
     329
    338330double * val = bsearch( 5.0, vals, 10 );        $\C{// selection based on return type}$
    339331int posn = bsearch( 5.0, vals, 10 );
     
    342334Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
    343335As well, an alternate kind of return is made available: position versus pointer to found element.
    344 \CC's type-system cannot disambiguate between the two versions of @bsearch@ because it does not use the return type in overload resolution, nor can \CC separately compile a template @bsearch@.
     336\CC's type-system cannot disambiguate between the two versions of @bsearch@ because it does not use the return type in overload resolution, nor can \CC separately compile a templated @bsearch@.
    345337
    346338\CFA has replacement libraries condensing hundreds of existing C functions into tens of \CFA overloaded functions, all without rewriting the actual computations (see Section~\ref{sec:libraries}).
     
    388380\begin{cfa}
    389381trait otype( dtype T | sized(T) ) {  // sized is a pseudo-trait for types with known size and alignment
    390         void ?{}( T & );                                                $\C{// default constructor}$
    391         void ?{}( T &, T );                                             $\C{// copy constructor}$
    392         void ?=?( T &, T );                                             $\C{// assignment operator}$
    393         void ^?{}( T & ); };                                    $\C{// destructor}$
     382        void ?{}( T * );                                                $\C{// default constructor}$
     383        void ?{}( T *, T );                                             $\C{// copy constructor}$
     384        void ?=?( T *, T );                                             $\C{// assignment operator}$
     385        void ^?{}( T * ); };                                    $\C{// destructor}$
    394386\end{cfa}
    395387Given the information provided for an @otype@, variables of polymorphic type can be treated as if they were a complete type: stack-allocatable, default or copy-initialized, assigned, and deleted.
     
    435427One approach is to write bespoke data-structures for each context in which they are needed.
    436428While this approach is flexible and supports integration with the C type-checker and tooling, it is also tedious and error-prone, especially for more complex data structures.
    437 A second approach is to use @void *@--based polymorphism, \eg the C standard-library functions @bsearch@ and @qsort@, which allow reuse of code with common functionality.
     429A second approach is to use @void *@--based polymorphism, \eg the C standard-library functions @bsearch@ and @qsort@, which allows reuse of code with common functionality.
    438430However, basing all polymorphism on @void *@ eliminates the type-checker's ability to ensure that argument types are properly matched, often requiring a number of extra function parameters, pointer indirection, and dynamic allocation that is not otherwise needed.
    439431A third approach to generic code is to use preprocessor macros, which does allow the generated code to be both generic and type-checked, but errors may be difficult to interpret.
    440 Furthermore, writing and using preprocessor macros is unnatural and inflexible.
     432Furthermore, writing and using preprocessor macros can be unnatural and inflexible.
    441433
    442434\CC, Java, and other languages use \newterm{generic types} to produce type-safe abstract data-types.
     
    450442        S second;
    451443};
    452 forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; } $\C{// dynamic}$
    453 forall( dtype F, otype T ) T value( pair( F *, T * ) p ) { return *p.second; } $\C{// dtype-static (concrete)}$
    454 
    455 pair( const char *, int ) p = { "magic", 42 }; $\C{// concrete}$
     444forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; }
     445forall( dtype F, otype T ) T value( pair( F *, T * ) p ) { return *p.second; }
     446
     447pair( const char *, int ) p = { "magic", 42 };
    456448int i = value( p );
    457 pair( void *, int * ) q = { 0, &p.second }; $\C{// concrete}$
     449pair( void *, int * ) q = { 0, &p.second };
    458450i = value( q );
    459451double d = 1.0;
    460 pair( double *, double * ) r = { &d, &d }; $\C{// concrete}$
     452pair( double *, double * ) r = { &d, &d };
    461453d = value( r );
    462454\end{cfa}
     
    464456\CFA classifies generic types as either \newterm{concrete} or \newterm{dynamic}.
    465457Concrete types have a fixed memory layout regardless of type parameters, while dynamic types vary in memory layout depending on their type parameters.
    466 A \newterm{dtype-static} type has polymorphic parameters but is still concrete.
     458A type may have polymorphic parameters but still be concrete, called \newterm{dtype-static}.
    467459Polymorphic pointers are an example of dtype-static types, \eg @forall(dtype T) T *@ is a polymorphic type, but for any @T@, @T *@  is a fixed-sized pointer, and therefore, can be represented by a @void *@ in code generation.
    468460
     
    481473For example, the concrete instantiation for @pair( const char *, int )@ is:
    482474\begin{cfa}
    483 struct _pair_conc0 {
     475struct _pair_conc1 {
    484476        const char * first;
    485477        int second;
     
    488480
    489481A concrete generic-type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations.
    490 In the above example, the @pair( F *, T * )@ parameter to @value@ is such a type; its expansion is below and it is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate:
    491 \begin{cfa}
    492 struct _pair_conc1 {
     482In the above example, the @pair( F *, T * )@ parameter to @value_p@ is such a type; its expansion is below and it is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate:
     483\begin{cfa}
     484struct _pair_conc0 {
    493485        void * first;
    494486        void * second;
     
    502494As mentioned in Section~\ref{sec:poly-fns}, @otype@ function parameters (in fact all @sized@ polymorphic parameters) come with implicit size and alignment parameters provided by the caller.
    503495Dynamic generic-types also have an \newterm{offset array} containing structure-member offsets.
    504 A dynamic generic-@union@ needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
     496A dynamic generic-union needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
    505497Access to members of a dynamic structure is provided at runtime via base-displacement addressing with the structure pointer and the member offset (similar to the @offsetof@ macro), moving a compile-time offset calculation to runtime.
    506498
    507499The offset arrays are statically generated where possible.
    508500If a dynamic generic-type is declared to be passed or returned by value from a polymorphic function, the translator can safely assume the generic type is complete (\ie has a known layout) at any call-site, and the offset array is passed from the caller;
    509 if the generic type is concrete at the call site, the elements of this offset array can even be statically generated using the C @offsetof@ macro.
    510 As an example, the body of the second @value@ function is implemented like this:
    511 \begin{cfa}
    512 _assign_T(_retval, p + _offsetof_pair[1]); $\C{// return *p.second}$
    513 \end{cfa}
    514 @_assign_T@ is passed in as an implicit parameter from @otype T@, and takes two @T*@ (@void*@ in the generated code), a destination and a source; @_retval@ is the pointer to a caller-allocated buffer for the return value, the usual \CFA method to handle dynamically-sized return types.
    515 @_offsetof_pair@ is the offset array passed into @value@; this array is generated at the call site as:
    516 \begin{cfa}
    517 size_t _offsetof_pair[] = { offsetof(_pair_conc0, first), offsetof(_pair_conc0, second) }
    518 \end{cfa}
     501if the generic type is concrete at the call site, the elements of this offset array can even be statically generated using the C @offsetof@ macro.
     502As an example, @p.second@ in the @value@ function above is implemented as @*(p + _offsetof_pair[1])@, where @p@ is a @void *@, and @_offsetof_pair@ is the offset array passed into @value@ for @pair( const char *, T )@.
     503The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) }@.
    519504
    520505In some cases the offset arrays cannot be statically generated.
     
    599584\subsection{Tuple Expressions}
    600585
    601 The addition of multiple-return-value functions (MRVF) are \emph{useless} without a syntax for accepting multiple values at the call-site.
     586The addition of multiple-return-value functions (MRVF) are useless without a syntax for accepting multiple values at the call-site.
    602587The simplest mechanism for capturing the return values is variable assignment, allowing the values to be retrieved directly.
    603588As such, \CFA allows assigning multiple values from a function into multiple variables, using a square-bracketed list of lvalue expressions (as above), called a \newterm{tuple}.
     
    835820\end{cfa}
    836821so the thunk provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
    837 These thunks take advantage of gcc C nested-functions to produce closures that have the usual function-pointer signature WHAT DOES THIS MEAN???.
     822These thunks take advantage of gcc C nested-functions to produce closures that have the usual function-pointer signature.
    838823
    839824
     
    891876        print(arg);  print(rest);
    892877}
    893 void print( const char * x ) { printf( "%s", x ); }
     878void print( char * x ) { printf( "%s", x ); }
    894879void print( int x ) { printf( "%d", x ); }
    895880void print( S s ) { print( "{ ", s.x, ",", s.y, " }" ); }
     
    900885The polymorphic @print@ allows printing any list of types, where as each individual type has a @print@ function.
    901886The individual print functions can be used to build up more complicated @print@ functions, such as @S@, which cannot be done with @printf@ in C.
    902 This mechanism is used to seamlessly print tuples in the \CFA I/O library (see Section~\ref{s:IOLibrary}).
    903887
    904888Finally, it is possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions.
     
    1004988\section{Control Structures}
    1005989
    1006 \CFA identifies inconsistent, problematic, and missing control structures in C, and extends, modifies, and adds to control structures to increase functionality and safety.
    1007 
    1008 
    1009 \subsection{\texorpdfstring{\LstKeywordStyle{if} Statement}{if Statement}}
    1010 
    1011 The @if@ expression allows declarations, similar to @for@ declaration expression:
    1012 \begin{cfa}
    1013 if ( int x = f() ) ...                                          $\C{// x != 0}$
    1014 if ( int x = f(), y = g() ) ...                         $\C{// x != 0 \&\& y != 0}$
    1015 if ( int x = f(), y = g(); `x < y` ) ...        $\C{// relational expression}$
    1016 \end{cfa}
    1017 Unless a relational expression is specified, each variable is compared not equal to 0, which is the standard semantics for the @if@ expression, and the results are combined using the logical @&&@ operator.\footnote{\CC only provides a single declaration always compared not equal to 0.}
    1018 The scope of the declaration(s) is local to the @if@ statement but exist within both the ``then'' and ``else'' clauses.
    1019 
    1020 
    1021 \subsection{\texorpdfstring{\LstKeywordStyle{switch} Statement}{switch Statement}}
    1022 
    1023 There are a number of deficiencies with the C @switch@ statements: enumerating @case@ lists, placement of @case@ clauses, scope of the switch body, and fall through between case clauses.
    1024 
    1025 C has no shorthand for specifying a list of case values, whether the list is non-contiguous or contiguous\footnote{C provides this mechanism via fall through.}.
    1026 \CFA provides a shorthand for a non-contiguous list:
    1027 \begin{cquote}
    1028 \lstDeleteShortInline@%
    1029 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
    1030 \multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
    1031 \begin{cfa}
    1032 case 2, 10, 34, 42:
    1033 \end{cfa}
    1034 &
    1035 \begin{cfa}
    1036 case 2: case 10: case 34: case 42:
    1037 \end{cfa}
    1038 \end{tabular}
    1039 \lstMakeShortInline@%
    1040 \end{cquote}
    1041 for a contiguous list:\footnote{gcc provides the same mechanism with awkward syntax, \lstinline@2 ... 42@, where spaces are required around the ellipse.}
    1042 \begin{cquote}
    1043 \lstDeleteShortInline@%
    1044 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
    1045 \multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
    1046 \begin{cfa}
    1047 case 2~42:
    1048 \end{cfa}
    1049 &
    1050 \begin{cfa}
    1051 case 2: case 3: ... case 41: case 42:
    1052 \end{cfa}
    1053 \end{tabular}
    1054 \lstMakeShortInline@%
    1055 \end{cquote}
    1056 and a combination:
    1057 \begin{cfa}
    1058 case -12~-4, -1~5, 14~21, 34~42:
    1059 \end{cfa}
    1060 
    1061 C allows placement of @case@ clauses \emph{within} statements nested in the @switch@ body (see Duff's device~\cite{Duff83});
    1062 \begin{cfa}
    1063 switch ( i ) {
    1064   case 0:
    1065         for ( int i = 0; i < 10; i += 1 ) {
    1066                 ...
    1067   `case 1:`             // no initialization of loop index
    1068                 ...
    1069         }
    1070 }
    1071 \end{cfa}
    1072 \CFA precludes this form of transfer into a control structure because it causes undefined behaviour, especially with respect to missed initialization, and provides very limited functionality.
    1073 
    1074 C allows placement of declaration within the @switch@ body and unreachable code at the start, resulting in undefined behaviour:
    1075 \begin{cfa}
    1076 switch ( x ) {
    1077         `int y = 1;`                                                    $\C{// unreachable initialization}$
    1078         `x = 7;`                                                                $\C{// unreachable code without label/branch}$
    1079   case 0:
    1080         ...
    1081         `int z = 0;`                                                    $\C{// unreachable initialization, cannot appear after case}$
    1082         z = 2;
    1083   case 1:
    1084         `x = z;`                                                                $\C{// without fall through, z is undefined}$
    1085 }
    1086 \end{cfa}
    1087 \CFA allows the declaration of local variables, \eg @y@, at the start of the @switch@ with scope across the entire @switch@ body, \ie all @case@ clauses.
    1088 \CFA disallows the declaration of local variable, \eg @z@, directly within the @switch@ body, because a declaration cannot occur immediately after a @case@ since a label can only be attached to a statement, and the use of @z@ is undefined in @case 1@ as neither storage allocation nor initialization may have occurred.
    1089 
    1090 C @switch@ provides multiple entry points into the statement body, but once an entry point is selected, control continues across \emph{all} @case@ clauses until the end of the @switch@ body, called \newterm{fall through};
    1091 @case@ clauses are made disjoint by the @break@ statement.
    1092 While the ability to fall through \emph{is} a useful form of control flow, it does not match well with programmer intuition, resulting in many errors from missing @break@ statements.
    1093 For backwards compatibility, \CFA provides a \emph{new} control structure, @choose@, which mimics @switch@, but reverses the meaning of fall through (see Figure~\ref{f:ChooseSwitchStatements}).
    1094 
    1095 Collectively, these enhancements reduce programmer burden and increase readability and safety.
    1096 
    1097 \begin{figure}
    1098 \centering
    1099 \lstDeleteShortInline@%
    1100 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    1101 \multicolumn{1}{c@{\hspace{2\parindentlnth}}}{\textbf{\CFA}}    & \multicolumn{1}{c}{\textbf{C}}        \\
    1102 \begin{cfa}
    1103 `choose` ( day ) {
    1104   case Mon~Thu:  // program
    1105 
    1106   case Fri:  // program
    1107         wallet += pay;
    1108         `fallthrough;`
    1109   case Sat:  // party
    1110         wallet -= party;
    1111 
    1112   case Sun:  // rest
    1113 
    1114   default:  // error
    1115 }
    1116 \end{cfa}
    1117 &
    1118 \begin{cfa}
    1119 switch ( day ) {
    1120   case Mon: case Tue: case Wed: case Thu:  // program
    1121         `break;`
    1122   case Fri:  // program
    1123         wallet += pay;
    1124 
    1125   case Sat:  // party
    1126         wallet -= party;
    1127         `break;`
    1128   case Sun:  // rest
    1129         `break;`
    1130   default:  // error
    1131 }
    1132 \end{cfa}
    1133 \end{tabular}
    1134 \lstMakeShortInline@%
    1135 \caption{\lstinline|choose| versus \lstinline|switch| Statements}
    1136 \label{f:ChooseSwitchStatements}
    1137 \end{figure}
    1138 
    1139 \begin{comment}
    1140 Forgotten @break@ statements at the end of @switch@ cases are a persistent sort of programmer error in C, and the @break@ statements themselves introduce visual clutter and an un-C-like keyword-based block delimiter.
    1141 \CFA addresses this error by introducing a @choose@ statement, which works identically to a @switch@ except that its default end-of-case behaviour is to break rather than to fall through for all non-empty cases.
    1142 Since empty cases like @case 7:@ in @case 7: case 11:@ still have fall-through semantics and explicit @break@ is still allowed at the end of a @choose@ case, many idiomatic uses of @switch@ in standard C can be converted to @choose@ statements by simply changing the keyword.
    1143 Where fall-through is desired for a non-empty case, it can be specified with the new @fallthrough@ statement, making @choose@ equivalently powerful to @switch@, but more concise in the common case where most non-empty cases end with a @break@ statement, as in the example below:
    1144 
    1145 \begin{cfa}
    1146 choose( i ) {
    1147         case 2:
    1148                 printf("even ");
    1149                 fallthrough;
    1150         case 3: case 5: case 7:
    1151                 printf("small prime\n");
    1152         case 4,6,8,9:
    1153                 printf("small composite\n");
    1154         case 13~19:
    1155                 printf("teen\n");
    1156         default:
    1157                 printf("something else\n");
    1158 }
    1159 \end{cfa}
    1160 \end{comment}
     990\CFA identifies missing and problematic control structures in C, and extends and modifies these control structures to increase functionality and safety.
    1161991
    1162992
     
    12181048                } else {
    12191049                        ... goto `LIF`; ...
    1220                 } `LIF:` ;
     1050                } `L3:` ;
    12211051        } `LS:` ;
    12221052} `LC:` ;
     
    12521082\end{figure}
    12531083
    1254 With respect to safety, both labelled @continue@ and @break@ are a @goto@ restricted in the following ways:
     1084Both labelled @continue@ and @break@ are a @goto@ restricted in the following ways:
    12551085\begin{itemize}
    12561086\item
     
    12651095With @goto@, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader.
    12661096Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs.
    1267 Otherwise, the implicit targets of the current @continue@ and @break@, \ie the closest enclosing loop or @switch@, change as certain constructs are added or removed.
    1268 
    1269 
    1270 \subsection{Exception Handling}
    1271 
    1272 The following framework for \CFA exception handling is in place, excluding some run-time type-information and dynamic casts.
    1273 \CFA provides two forms of exception handling: \newterm{fix-up} and \newterm{recovery} (see Figure~\ref{f:CFAExceptionHandling})~\cite{Buhr92b,Buhr00a}.
    1274 Both mechanisms provide dynamic call to a handler using dynamic name-lookup, where fix-up has dynamic return and recovery has static return from the handler.
    1275 \CFA restricts exception types to those defined by aggregate type @exception@.
    1276 The form of the raise dictates the set of handlers examined during propagation: \newterm{resumption propagation} (@resume@) only examines resumption handlers (@catchResume@); \newterm{terminating propagation} (@throw@) only examines termination handlers (@catch@).
    1277 If @resume@ or @throw@ have no exception type, it is a reresume/rethrow, meaning the currently exception continues propagation.
    1278 If there is no current exception, the reresume/rethrow results in a runtime error.
    1279 
    1280 \begin{figure}
     1097The implicit targets of the current @continue@ and @break@, \ie the closest enclosing loop or @switch@, change as certain constructs are added or removed.
     1098
     1099
     1100\subsection{\texorpdfstring{Enhanced \LstKeywordStyle{switch} Statement}{Enhanced switch Statement}}
     1101
     1102There are a number of deficiencies with the C @switch@ statements: enumerating @case@ lists, placement of @case@ clauses, scope of the switch body, and fall through between case clauses.
     1103
     1104C has no shorthand for specifying a list of case values, whether the list is non-contiguous or contiguous\footnote{C provides this mechanism via fall through.}.
     1105\CFA provides a shorthand for a non-contiguous list:
    12811106\begin{cquote}
    12821107\lstDeleteShortInline@%
    1283 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    1284 \multicolumn{1}{c@{\hspace{2\parindentlnth}}}{\textbf{Resumption}}      & \multicolumn{1}{c}{\textbf{Termination}}      \\
    1285 \begin{cfa}
    1286 `exception R { int fix; };`
    1287 void f() {
    1288         R r;
    1289         ... `resume( r );` ...
    1290         ... r.fix // control does return here after handler
    1291 }
    1292 `try` {
    1293         ... f(); ...
    1294 } `catchResume( R r )` {
    1295         ... r.fix = ...; // return correction to raise
    1296 } // dynamic return to _Resume
    1297 \end{cfa}
    1298 &
    1299 \begin{cfa}
    1300 `exception T {};`
    1301 void f() {
    1302 
    1303         ... `throw( T{} );` ...
    1304         // control does NOT return here after handler
    1305 }
    1306 `try` {
    1307         ... f(); ...
    1308 } `catch( T t )` {
    1309         ... // recover and continue
    1310 } // static return to next statement
     1108\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
     1109\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
     1110\begin{cfa}
     1111case 2, 10, 34, 42:
     1112\end{cfa}
     1113&
     1114\begin{cfa}
     1115case 2: case 10: case 34: case 42:
    13111116\end{cfa}
    13121117\end{tabular}
    13131118\lstMakeShortInline@%
    13141119\end{cquote}
    1315 \caption{\CFA Exception Handling}
    1316 \label{f:CFAExceptionHandling}
    1317 \end{figure}
    1318 
    1319 The set of exception types in a list of catch clause may include both a resumption and termination handler:
    1320 \begin{cfa}
    1321 try {
    1322         ... resume( `R{}` ); ...
    1323 } catchResume( `R` r ) { ... throw( R{} ); ... } $\C{\color{red}// H1}$
    1324    catch( `R` r ) { ... }                                       $\C{\color{red}// H2}$
    1325 
    1326 \end{cfa}
    1327 The resumption propagation raises @R@ and the stack is not unwound;
    1328 the exception is caught by the @catchResume@ clause and handler H1 is invoked.
    1329 The termination propagation in handler H1 raises @R@ and the stack is unwound;
    1330 the exception is caught by the @catch@ clause and handler H2 is invoked.
    1331 The termination handler is available because the resumption propagation did not unwind the stack.
    1332 
    1333 An additional feature is conditional matching in a catch clause:
    1334 \begin{cfa}
    1335 try {
    1336         ... write( `datafile`, ... ); ...               $\C{// may throw IOError}$
    1337         ... write( `logfile`, ... ); ...
    1338 } catch ( IOError err; `err.file == datafile` ) { ... } $\C{// handle datafile error}$
    1339    catch ( IOError err; `err.file == logfile` ) { ... } $\C{// handle logfile error}$
    1340    catch ( IOError err ) { ... }                        $\C{// handler error from other files}$
    1341 \end{cfa}
    1342 where the throw inserts the failing file-handle in the I/O exception.
    1343 Conditional catch cannot be trivially mimicked by other mechanisms because once an exception is caught, handler clauses in that @try@ statement are no longer eligible..
    1344 
    1345 The resumption raise can specify an alternate stack on which to raise an exception, called a \newterm{nonlocal raise}:
    1346 \begin{cfa}
    1347 resume( $\emph{exception-type}$, $\emph{alternate-stack}$ )
    1348 resume( $\emph{alternate-stack}$ )
    1349 \end{cfa}
    1350 These overloads of @resume@ raise the specified exception or the currently propagating exception (reresume) at another \CFA coroutine or task~\cite{Delisle18}.\footnote{\CFA coroutine and concurrency features are discussed in a separately submitted paper.}
    1351 Nonlocal raise is restricted to resumption to provide the exception handler the greatest flexibility because processing the exception does not unwind its stack, allowing it to continue after the handle returns.
    1352 
    1353 To facilitate nonlocal exception, \CFA provides dynamic enabling and disabling of nonlocal exception-propagation.
    1354 The constructs for controlling propagation of nonlocal exceptions are the @enable@ and the @disable@ blocks:
     1120for a contiguous list:\footnote{gcc provides the same mechanism with awkward syntax, \lstinline@2 ... 42@, where spaces are required around the ellipse.}
    13551121\begin{cquote}
    13561122\lstDeleteShortInline@%
    1357 \begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
    1358 \begin{cfa}
    1359 enable $\emph{exception-type-list}$ {
    1360         // allow non-local resumption
    1361 }
    1362 \end{cfa}
    1363 &
    1364 \begin{cfa}
    1365 disable $\emph{exception-type-list}$ {
    1366         // disallow non-local resumption
    1367 }
     1123\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
     1124\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
     1125\begin{cfa}
     1126case 2~42:
     1127\end{cfa}
     1128&
     1129\begin{cfa}
     1130case 2: case 3: ... case 41: case 42:
    13681131\end{cfa}
    13691132\end{tabular}
    13701133\lstMakeShortInline@%
    13711134\end{cquote}
    1372 The arguments for @enable@/@disable@ specify the exception types allowed to be propagated or postponed, respectively.
    1373 Specifying no exception type is shorthand for specifying all exception types.
    1374 Both @enable@ and @disable@ blocks can be nested, turning propagation on/off on entry, and on exit, the specified exception types are restored to their prior state.
    1375 Coroutines and tasks start with non-local exceptions disabled, allowing handlers to be put in place, before non-local exceptions are explicitly enabled.
    1376 \begin{cfa}
    1377 void main( mytask & c ) {
    1378         try {
    1379                 enable {                        $\C{// now allow non-local exception delivery}$
    1380                         // task body
    1381                 }
    1382         // appropriate catchResume/catch
     1135and a combination:
     1136\begin{cfa}
     1137case -12~-4, -1~5, 14~21, 34~42:
     1138\end{cfa}
     1139
     1140C allows placement of @case@ clauses \emph{within} statements nested in the @switch@ body (see Duff's device~\cite{Duff83});
     1141\begin{cfa}
     1142switch ( i ) {
     1143  case 0:
     1144        for ( int i = 0; i < 10; i += 1 ) {
     1145                ...
     1146  `case 1:`             // no initialization of loop index
     1147                ...
    13831148        }
    13841149}
    13851150\end{cfa}
    1386 
    1387 Finally, \CFA provides a Java like  @finally@ clause after the catch clauses:
    1388 \begin{cfa}
    1389 try {
    1390         ... f(); ...
    1391 // catchResume or catch clauses
    1392 } `finally` {
    1393         // house keeping
    1394 }
    1395 \end{cfa}
    1396 The finally clause is always executed, i.e., if the try block ends normally or if an exception is raised.
    1397 If an exception is raised and caught, the handler is run before the finally clause.
    1398 Like a destructor (see Section~\ref{s:ConstructorsDestructors}), a finally clause can raise an exception but not if there is an exception being propagated.
    1399 Mimicking the @finally@ clause with mechanisms like RAII is non-trivially when there are multiple types and local accesses.
     1151\CFA precludes this form of transfer into a control structure because it causes undefined behaviour, especially with respect to missed initialization, and provides very limited functionality.
     1152
     1153C allows placement of declaration within the @switch@ body and unreachable code at the start, resulting in undefined behaviour:
     1154\begin{cfa}
     1155switch ( x ) {
     1156        `int y = 1;`                            $\C{// unreachable initialization}$
     1157        `x = 7;`                                        $\C{// unreachable code without label/branch}$
     1158  case 0:
     1159        ...
     1160        `int z = 0;`                            $\C{// unreachable initialization, cannot appear after case}$
     1161        z = 2;
     1162  case 1:
     1163        `x = z;`                                        $\C{// without fall through, z is undefined}$
     1164}
     1165\end{cfa}
     1166\CFA allows the declaration of local variables, \eg @y@, at the start of the @switch@ with scope across the entire @switch@ body, \ie all @case@ clauses.
     1167\CFA disallows the declaration of local variable, \eg @z@, directly within the @switch@ body, because a declaration cannot occur immediately after a @case@ since a label can only be attached to a statement, and the use of @z@ is undefined in @case 1@ as neither storage allocation nor initialization may have occurred.
     1168
     1169C @switch@ provides multiple entry points into the statement body, but once an entry point is selected, control continues across \emph{all} @case@ clauses until the end of the @switch@ body, called \newterm{fall through};
     1170@case@ clauses are made disjoint by the @break@ statement.
     1171While the ability to fall through \emph{is} a useful form of control flow, it does not match well with programmer intuition, resulting in many errors from missing @break@ statements.
     1172For backwards compatibility, \CFA provides a \emph{new} control structure, @choose@, which mimics @switch@, but reverses the meaning of fall through (see Figure~\ref{f:ChooseSwitchStatements}).
     1173Collectively, these enhancements reduce programmer burden and increase readability and safety.
     1174
     1175\begin{figure}
     1176\centering
     1177\lstDeleteShortInline@%
     1178\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
     1179\multicolumn{1}{c@{\hspace{2\parindentlnth}}}{\textbf{\CFA}}    & \multicolumn{1}{c}{\textbf{C}}        \\
     1180\begin{cfa}
     1181`choose` ( day ) {
     1182  case Mon~Thu:  // program
     1183
     1184  case Fri:  // program
     1185        wallet += pay;
     1186        `fallthrough;`
     1187  case Sat:  // party
     1188        wallet -= party;
     1189
     1190  case Sun:  // rest
     1191
     1192  default:  // error
     1193}
     1194\end{cfa}
     1195&
     1196\begin{cfa}
     1197switch ( day ) {
     1198  case Mon: case Tue: case Wed: case Thu:  // program
     1199        `break;`
     1200  case Fri:  // program
     1201        wallet += pay;
     1202
     1203  case Sat:  // party
     1204        wallet -= party;
     1205        `break;`
     1206  case Sun:  // rest
     1207        `break;`
     1208  default:  // error
     1209}
     1210\end{cfa}
     1211\end{tabular}
     1212\lstMakeShortInline@%
     1213\caption{\lstinline|choose| versus \lstinline|switch| Statements}
     1214\label{f:ChooseSwitchStatements}
     1215\end{figure}
     1216
     1217\begin{comment}
     1218Forgotten @break@ statements at the end of @switch@ cases are a persistent sort of programmer error in C, and the @break@ statements themselves introduce visual clutter and an un-C-like keyword-based block delimiter.
     1219\CFA addresses this error by introducing a @choose@ statement, which works identically to a @switch@ except that its default end-of-case behaviour is to break rather than to fall through for all non-empty cases.
     1220Since empty cases like @case 7:@ in @case 7: case 11:@ still have fall-through semantics and explicit @break@ is still allowed at the end of a @choose@ case, many idiomatic uses of @switch@ in standard C can be converted to @choose@ statements by simply changing the keyword.
     1221Where fall-through is desired for a non-empty case, it can be specified with the new @fallthrough@ statement, making @choose@ equivalently powerful to @switch@, but more concise in the common case where most non-empty cases end with a @break@ statement, as in the example below:
     1222
     1223\begin{cfa}
     1224choose( i ) {
     1225        case 2:
     1226                printf("even ");
     1227                fallthrough;
     1228        case 3: case 5: case 7:
     1229                printf("small prime\n");
     1230        case 4,6,8,9:
     1231                printf("small composite\n");
     1232        case 13~19:
     1233                printf("teen\n");
     1234        default:
     1235                printf("something else\n");
     1236}
     1237\end{cfa}
     1238\end{comment}
    14001239
    14011240
     
    14121251S s, as[10];
    14131252\end{cfa}
    1414 However, functions manipulating aggregates must repeat the aggregate name to access its containing fields:
     1253However, routines manipulating aggregates must repeat the aggregate name to access its containing fields:
    14151254\begin{cfa}
    14161255void f( S s ) {
     
    14301269}
    14311270\end{C++}
    1432 Object-oriented nesting of member functions in a \lstinline[language=C++]@class@ allows eliding \lstinline[language=C++]@this->@ because of lexical scoping.
     1271Object-oriented nesting of member routines in a \lstinline[language=C++]@class@ allows eliding \lstinline[language=C++]@this->@ because of lexical scoping.
    14331272However, for other aggregate parameters, qualification is necessary:
    14341273\begin{cfa}
     
    14601299        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
    14611300\end{cfa}
    1462 and may appear as the body of a function or nested within a function body.
     1301and may appear as the body of a routine or nested within a routine body.
    14631302Each expression in the expression-list provides a type and object.
    14641303The type must be an aggregate type.
     
    14871326Qualification or a cast is used to disambiguate.
    14881327
    1489 There is an interesting problem between parameters and the function-body @with@, \eg:
     1328There is an interesting problem between parameters and the routine @with@, \eg:
    14901329\begin{cfa}
    14911330void ?{}( S & s, int i ) with ( s ) {           $\C{// constructor}$
     
    14931332}
    14941333\end{cfa}
    1495 Here, the assignment @s.i = i@ means @s.i = s.i@, which is meaningless, and there is no mechanism to qualify the parameter @i@, making the assignment impossible using the function-body @with@.
     1334Here, the assignment @s.i = i@ means @s.i = s.i@, which is meaningless, and there is no mechanism to qualify the parameter @i@, making the assignment impossible using the routine @with@.
    14961335To solve this problem, parameters are treated like an initialized aggregate:
    14971336\begin{cfa}
     
    15011340} params;
    15021341\end{cfa}
    1503 and implicitly opened \emph{after} a function-body open, to give them higher priority:
    1504 \begin{cfa}
    1505 void ?{}( S & s, int `i` ) with ( s ) `with( $\emph{\color{red}params}$ )` {
    1506         s.i = `i`; j = 3; m = 5.5;
     1342and implicitly opened \emph{after} a routine open, to give them higher priority:
     1343\begin{cfa}
     1344void ?{}( S & s, int i ) with ( s ) `with( $\emph{\color{red}params}$ )` {
     1345        s.i = i; j = 3; m = 5.5;
    15071346}
    15081347\end{cfa}
     
    15291368
    15301369
     1370\subsection{Exception Handling}
     1371
     1372The following framework for \CFA exception handling is in place, excluding a run-time type information and dynamic casts.
     1373\CFA provides two forms of exception handling: \newterm{fix-up} and \newterm{recovery} (see Figure~\ref{f:CFAExceptionHandling}).
     1374Both mechanisms provide dynamic call to a handler using dynamic name-lookup, where fix-up has dynamic return and recovery has static return from the handler.
     1375\CFA restricts exception types to those defined by aggregate type @exception@.
     1376The form of the raise dictates the set of handlers examined during propagation: \newterm{resumption propagation} (@resume@) only examines resumption handlers (@catchResume@); \newterm{terminating propagation} (@throw@) only examines termination handlers (@catch@).
     1377If @resume@ or @throw@ have no exception type, it is a reresume/rethrow, meaning the currently exception continues propagation.
     1378If there is no current exception, the reresume/rethrow results in a runtime error.
     1379
     1380\begin{figure}
     1381\begin{cquote}
     1382\lstDeleteShortInline@%
     1383\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
     1384\multicolumn{1}{c@{\hspace{2\parindentlnth}}}{\textbf{Resumption}}      & \multicolumn{1}{c}{\textbf{Termination}}      \\
     1385\begin{cfa}
     1386`exception R { int fix; };`
     1387void f() {
     1388        R r;
     1389        ... `resume( r );` ...
     1390        ... r.fix // control does return here after handler
     1391}
     1392`try` {
     1393        ... f(); ...
     1394} `catchResume( R r )` {
     1395        ... r.fix = ...; // return correction to raise
     1396} // dynamic return to _Resume
     1397\end{cfa}
     1398&
     1399\begin{cfa}
     1400`exception T {};`
     1401void f() {
     1402
     1403        ... `throw( T{} );` ...
     1404        // control does NOT return here after handler
     1405}
     1406`try` {
     1407        ... f(); ...
     1408} `catch( T t )` {
     1409        ... // recover and continue
     1410} // static return to next statement
     1411\end{cfa}
     1412\end{tabular}
     1413\lstMakeShortInline@%
     1414\end{cquote}
     1415\caption{\CFA Exception Handling}
     1416\label{f:CFAExceptionHandling}
     1417\end{figure}
     1418
     1419The set of exception types in a list of catch clause may include both a resumption and termination handler:
     1420\begin{cfa}
     1421try {
     1422        ... resume( `R{}` ); ...
     1423} catchResume( `R` r ) { ... throw( R{} ); ... } $\C{\color{red}// H1}$
     1424   catch( `R` r ) { ... }                                       $\C{\color{red}// H2}$
     1425
     1426\end{cfa}
     1427The resumption propagation raises @R@ and the stack is not unwound;
     1428the exception is caught by the @catchResume@ clause and handler H1 is invoked.
     1429The termination propagation in handler H1 raises @R@ and the stack is unwound;
     1430the exception is caught by the @catch@ clause and handler H2 is invoked.
     1431The termination handler is available because the resumption propagation did not unwind the stack.
     1432
     1433An additional feature is conditional matching in a catch clause:
     1434\begin{cfa}
     1435try {
     1436        ... write( `datafile`, ... ); ...               $\C{// may throw IOError}$
     1437        ... write( `logfile`, ... ); ...
     1438} catch ( IOError err; `err.file == datafile` ) { ... } $\C{// handle datafile error}$
     1439   catch ( IOError err; `err.file == logfile` ) { ... } $\C{// handle logfile error}$
     1440   catch ( IOError err ) { ... }                        $\C{// handler error from other files}$
     1441\end{cfa}
     1442where the throw inserts the failing file-handle in the I/O exception.
     1443Conditional catch cannot be trivially mimicked by other mechanisms because once an exception is caught, handler clauses in that @try@ statement are no longer eligible..
     1444
     1445The resumption raise can specify an alternate stack on which to raise an exception, called a \newterm{nonlocal raise}:
     1446\begin{cfa}
     1447resume( $\emph{exception-type}$, $\emph{alternate-stack}$ )
     1448resume( $\emph{alternate-stack}$ )
     1449\end{cfa}
     1450These overloads of @resume@ raise the specified exception or the currently propagating exception (reresume) at another coroutine or task~\cite{Delisle18}.
     1451Nonlocal raise is restricted to resumption to provide the exception handler the greatest flexibility because processing the exception does not unwind its stack, allowing it to continue after the handle returns.
     1452
     1453To facilitate nonlocal exception, \CFA provides dynamic enabling and disabling of nonlocal exception-propagation.
     1454The constructs for controlling propagation of nonlocal exceptions are the @enable@ and the @disable@ blocks:
     1455\begin{cquote}
     1456\lstDeleteShortInline@%
     1457\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
     1458\begin{cfa}
     1459enable $\emph{exception-type-list}$ {
     1460        // allow non-local resumption
     1461}
     1462\end{cfa}
     1463&
     1464\begin{cfa}
     1465disable $\emph{exception-type-list}$ {
     1466        // disallow non-local resumption
     1467}
     1468\end{cfa}
     1469\end{tabular}
     1470\lstMakeShortInline@%
     1471\end{cquote}
     1472The arguments for @enable@/@disable@ specify the exception types allowed to be propagated or postponed, respectively.
     1473Specifying no exception type is shorthand for specifying all exception types.
     1474Both @enable@ and @disable@ blocks can be nested, turning propagation on/off on entry, and on exit, the specified exception types are restored to their prior state.
     1475
     1476Finally, \CFA provides a Java like  @finally@ clause after the catch clauses:
     1477\begin{cfa}
     1478try {
     1479        ... f(); ...
     1480// catchResume or catch clauses
     1481} `finally` {
     1482        // house keeping
     1483}
     1484\end{cfa}
     1485The finally clause is always executed, i.e., if the try block ends normally or if an exception is raised.
     1486If an exception is raised and caught, the handler is run before the finally clause.
     1487Like a destructor (see Section~\ref{s:ConstructorsDestructors}), a finally clause can raise an exception but not if there is an exception being propagated.
     1488Mimicking the @finally@ clause with mechanisms like RAII is non-trivially when there are multiple types and local accesses.
     1489
     1490
    15311491\section{Declarations}
    15321492
     
    15561516Is this an array of 5 pointers to integers or a pointer to an array of 5 integers?
    15571517If there is any doubt, it implies productivity and safety issues even for basic programs.
    1558 Another example of confusion results from the fact that a function name and its parameters are embedded within the return type, mimicking the way the return value is used at the function's call site.
    1559 For example, a function returning a pointer to an array of integers is defined and used in the following way:
     1518Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site.
     1519For example, a routine returning a pointer to an array of integers is defined and used in the following way:
    15601520\begin{cfa}
    15611521int `(*`f`())[`5`]` {...};                                      $\C{// definition}$
    15621522 ... `(*`f`())[`3`]` += 1;                                      $\C{// usage}$
    15631523\end{cfa}
    1564 Essentially, the return type is wrapped around the function name in successive layers (like an onion).
     1524Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
    15651525While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice.
    15661526
    1567 \CFA provides its own type, variable and function declarations, using a different syntax~\cite[pp.~856--859]{Buhr94a}.
     1527\CFA provides its own type, variable and routine declarations, using a different syntax.
    15681528The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right.
    15691529The qualifiers have the same meaning but are ordered left to right to specify a variable's type.
     
    15931553\end{cquote}
    15941554The only exception is bit field specification, which always appear to the right of the base type.
    1595 % Specifically, the character @*@ is used to indicate a pointer, square brackets @[@\,@]@ are used to represent an array or function return value, and parentheses @()@ are used to indicate a function parameter.
     1555% Specifically, the character @*@ is used to indicate a pointer, square brackets @[@\,@]@ are used to represent an array or function return value, and parentheses @()@ are used to indicate a routine parameter.
    15961556However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list.
    15971557For instance, variables @x@ and @y@ of type pointer to integer are defined in \CFA as follows:
     
    16791639\lstMakeShortInline@%
    16801640\end{cquote}
    1681 Specifiers must appear at the start of a \CFA function declaration\footnote{\label{StorageClassSpecifier}
     1641Specifiers must appear at the start of a \CFA routine declaration\footnote{\label{StorageClassSpecifier}
    16821642The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}}.
    16831643
    1684 The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-function @sizeof@:
     1644The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine @sizeof@:
    16851645\begin{cquote}
    16861646\lstDeleteShortInline@%
     
    17001660\end{cquote}
    17011661
    1702 The syntax of the new function-prototype declaration follows directly from the new function-definition syntax;
     1662The syntax of the new routine prototype declaration follows directly from the new routine definition syntax;
    17031663as well, parameter names are optional, \eg:
    17041664\begin{cfa}
     
    17091669[ * int, int ] j ( int );                                       $\C{// returning pointer to int and int, with int parameter}$
    17101670\end{cfa}
    1711 This syntax allows a prototype declaration to be created by cutting and pasting source text from the function-definition header (or vice versa).
    1712 Like C, it is possible to declare multiple function-prototypes in a single declaration, where the return type is distributed across \emph{all} function names in the declaration list, \eg:
     1671This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
     1672Like C, it is possible to declare multiple routine-prototypes in a single declaration, where the return type is distributed across \emph{all} routine names in the declaration list, \eg:
    17131673\begin{cquote}
    17141674\lstDeleteShortInline@%
     
    17251685\lstMakeShortInline@%
    17261686\end{cquote}
    1727 where \CFA allows the last function in the list to define its body.
    1728 
    1729 The syntax for pointers to \CFA functions specifies the pointer name on the right, \eg:
    1730 \begin{cfa}
    1731 * [ int x ] () fp;                                                      $\C{// pointer to function returning int with no parameters}$
    1732 * [ * int ] ( int y ) gp;                                       $\C{// pointer to function returning pointer to int with int parameter}$
    1733 * [ ] ( int, char ) hp;                                         $\C{// pointer to function returning no result with int and char parameters}$
    1734 * [ * int, int ] ( int ) jp;                            $\C{// pointer to function returning pointer to int and int, with int parameter}$
    1735 \end{cfa}
    1736 Note, a function name cannot be specified:
    1737 \begin{cfa}
    1738 * [ int x ] f () fp;                                            $\C{// function name "f" is disallowed}$
     1687where \CFA allows the last routine in the list to define its body.
     1688
     1689The syntax for pointers to \CFA routines specifies the pointer name on the right, \eg:
     1690\begin{cfa}
     1691* [ int x ] () fp;                                                      $\C{// pointer to routine returning int with no parameters}$
     1692* [ * int ] ( int y ) gp;                                       $\C{// pointer to routine returning pointer to int with int parameter}$
     1693* [ ] ( int, char ) hp;                                         $\C{// pointer to routine returning no result with int and char parameters}$
     1694* [ * int, int ] ( int ) jp;                            $\C{// pointer to routine returning pointer to int and int, with int parameter}$
     1695\end{cfa}
     1696Note, a routine name cannot be specified:
     1697\begin{cfa}
     1698* [ int x ] f () fp;                                            $\C{// routine name "f" is disallowed}$
    17391699\end{cfa}
    17401700
     
    19561916Destruction parameters are useful for specifying storage-management actions, such as de-initialize but not deallocate.}.
    19571917\begin{cfa}
    1958 struct VLA { int len, * data; };
    1959 void ?{}( VLA & vla ) with ( vla ) { len = 10;  data = alloc( len ); }  $\C{// default constructor}$
    1960 void ^?{}( VLA & vla ) with ( vla ) { free( data ); } $\C{// destructor}$
     1918struct VLA {
     1919        int len, * data;
     1920};
     1921void ?{}( VLA & vla ) with ( vla ) {            $\C{// default constructor}$
     1922        len = 10;  data = alloc( len );                 $\C{// shallow copy}$
     1923}
     1924void ^?{}( VLA & vla ) with ( vla ) {           $\C{// destructor}$
     1925        free( data );
     1926}
    19611927{
    19621928        VLA x;                                                                  $\C{// implicit:  ?\{\}( x );}$
    19631929}                                                                                       $\C{// implicit:  ?\^{}\{\}( x );}$
    19641930\end{cfa}
     1931(Note, the example is purposely kept simple by using shallow-copy semantics.)
    19651932@VLA@ is a \newterm{managed type}\footnote{
    19661933A managed type affects the runtime environment versus a self-contained type.}: a type requiring a non-trivial constructor or destructor, or with a field of a managed type.
     
    19701937\CFA also provides syntax for \newterm{initialization} and \newterm{copy}:
    19711938\begin{cfa}
    1972 void ?{}( VLA & vla, int size, char fill ) with ( vla ) {  $\C{// initialization}$
     1939void ?{}( VLA & vla, int size, char fill ) with ( vla ) {       $\C{// initialization}$
    19731940        len = size;  data = alloc( len, fill );
    19741941}
    1975 void ?{}( VLA & vla, VLA other ) {                      $\C{// copy, shallow}$
     1942void ?{}( VLA & vla, VLA other ) {                      $\C{// copy}$
    19761943        vla.len = other.len;  vla.data = other.data;
    19771944}
    19781945\end{cfa}
    1979 (Note, the example is purposely simplified using shallow-copy semantics.)
    19801946An initialization constructor-call has the same syntax as a C initializer, except the initialization values are passed as arguments to a matching constructor (number and type of paremeters).
    19811947\begin{cfa}
     
    19911957\begin{cfa}
    19921958{
    1993         VLA  x,            y = { 20, 0x01 },     z = y; $\C{// z points to y}$
    1994         //      ?{}( x );  ?{}( y, 20, 0x01 );  ?{}( z, y );
     1959        VLA x,  y = { 20, 0x01 },  z = y;
     1960        // implicit:  ?{}( x );  ?{}( y, 20, 0x01 );  ?{}( z, y ); z points to y
    19951961        ^x{};                                                                   $\C{// deallocate x}$
    19961962        x{};                                                                    $\C{// reallocate x}$
     
    19991965        y{ x };                                                                 $\C{// reallocate y, points to x}$
    20001966        x{};                                                                    $\C{// reallocate x, not pointing to y}$
    2001         // ^?{}(z);  ^?{}(y);  ^?{}(x);
     1967        // implicit:  ^?{}(z);  ^?{}(y);  ^?{}(x);
    20021968}
    20031969\end{cfa}
     
    20301996C already includes limited polymorphism for literals -- @0@ can be either an integer or a pointer literal, depending on context, while the syntactic forms of literals of the various integer and float types are very similar, differing from each other only in suffix.
    20311997In keeping with the general \CFA approach of adding features while respecting the ``C-style'' of doing things, C's polymorphic constants and typed literal syntax are extended to interoperate with user-defined types, while maintaining a backwards-compatible semantics.
    2032 
    2033 A simple example is allowing the underscore, as in Ada, to separate prefixes, digits, and suffixes in all \CFA constants, \eg @0x`_`1.ffff`_`ffff`_`p`_`128`_`l@, where the underscore is also the standard separator in C identifiers.
    2034 \CC uses a single quote as a separator but it is restricted among digits, precluding its use in the literal prefix or suffix, \eg @0x1.ffff@@`'@@ffffp128l@, and causes problems with most IDEs, which must be extended to deal with this alternate use of the single quote.
    2035 
    2036 
    2037 \subsection{Integral Suffixes}
    2038 
    2039 Additional integral suffixes are added to cover all the integral types and lengths.
    2040 \begin{cquote}
    2041 \lstDeleteShortInline@%
    2042 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
    2043 \begin{cfa}
    2044 20_`hh`     // signed char
    2045 21_`hhu`   // unsigned char
    2046 22_`h`       // signed short int
    2047 23_`uh`     // unsigned short int
    2048 24_`z`       // size_t
    2049 \end{cfa}
    2050 &
    2051 \begin{cfa}
    2052 20_`L8`      // int8_t
    2053 21_`ul8`     // uint8_t
    2054 22_`l16`     // int16_t
    2055 23_`ul16`   // uint16_t
    2056 24_`l32`     // int32_t
    2057 \end{cfa}
    2058 &
    2059 \begin{cfa}
    2060 25_`ul32`      // uint32_t
    2061 26_`l64`        // int64_t
    2062 27_`l64u`      // uint64_t
    2063 26_`L128`     // int128
    2064 27_`L128u`   // unsigned int128
    2065 \end{cfa}
    2066 \end{tabular}
    2067 \lstMakeShortInline@%
    2068 \end{cquote}
     1998A trivial example is allowing the underscore to separate prefixes, digits, and suffixes in all \CFA constants, as in Ada, \eg @0x`_`1.ffff`_`ffff`_`p`_`128`_`l@.
    20691999
    20702000
     
    20832013
    20842014
    2085 \subsection{User Literals}
    2086 
    2087 For readability, it is useful to associate units to scale literals, \eg weight (stone, pound, kilogram) or time (seconds, minutes, hours).
    2088 The left of Figure~\ref{f:UserLiteral} shows the \CFA alternative call-syntax (literal argument before function name), using the backquote, to convert basic literals into user literals.
    2089 The backquote is a small character, making the unit (function name) predominate.
    2090 For examples, the multi-precision integers in Section~\ref{s:MultiPrecisionIntegers} make use of user literals:
    2091 {\lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
    2092 \begin{cfa}
    2093 y = 9223372036854775807L|`mp| * 18446744073709551615UL|`mp|;
    2094 y = "12345678901234567890123456789"|`mp| + "12345678901234567890123456789"|`mp|;
    2095 \end{cfa}
    2096 Because \CFA uses a standard function, all types and literals are applicable, as well as overloading and conversions.
    2097 }%
    2098 
    2099 The right of Figure~\ref{f:UserLiteral} shows the equivalent \CC version using the underscore for the call-syntax.
    2100 However, \CC restricts the types, \eg @unsigned long long int@ and @long double@ to represent integral and floating literals.
    2101 After which, user literals must match (no conversions);
    2102 hence, it is necessary to overload the unit with all appropriate types.
    2103 
    2104 \begin{figure}
    2105 \centering
    2106 \lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
     2015\subsection{Integral Suffixes}
     2016
     2017Additional integral suffixes are added to cover all the integral types and lengths.
     2018\begin{cquote}
    21072019\lstDeleteShortInline@%
    2108 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
    2109 \multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{\CC}}      \\
    2110 \begin{cfa}
    2111 struct W {
    2112         double stones;
    2113 };
    2114 void ?{}( W & w ) { w.stones = 0; }
    2115 void ?{}( W & w, double w ) { w.stones = w; }
    2116 W ?+?( W l, W r ) {
    2117         return (W){ l.stones + r.stones };
    2118 }
    2119 W |?`st|( double w ) { return (W){ w }; }
    2120 W |?`lb|( double w ) { return (W){ w / 14.0 }; }
    2121 W |?`kg|( double w ) { return (W) { w * 0.16 }; }
    2122 
    2123 
    2124 
    2125 int main() {
    2126         W w, heavy = { 20 };
    2127         w = 155|`lb|;
    2128         w = 0b_1111|`st|;
    2129         w = 0_233|`lb|;
    2130         w = 0x_9b_u|`kg|;
    2131         w = 5.5|`st| + 8|`kg| + 25.01|`lb| + heavy;
    2132 }
    2133 \end{cfa}
    2134 &
    2135 \begin{cfa}
    2136 struct W {
    2137     double stones;
    2138     W() { stones = 0.0; }
    2139     W( double w ) { stones = w; }
    2140 };
    2141 W operator+( W l, W r ) {
    2142         return W( l.stones + r.stones );
    2143 }
    2144 W |operator"" _st|( unsigned long long int w ) { return W( w ); }
    2145 W |operator"" _lb|( unsigned long long int w ) { return W( w / 14.0 ); }
    2146 W |operator"" _kg|( unsigned long long int w ) { return W( w * 0.16 ); }
    2147 W |operator"" _st|( long double w ) { return W( w ); }
    2148 W |operator"" _lb|( long double w ) { return W( w / 14.0 ); }
    2149 W |operator"" _kg|( long double w ) { return W( w * 0.16 ); }
    2150 int main() {
    2151         W w, heavy = { 20 };
    2152         w = 155|_lb|;
    2153         w = 0b1111|_lb|;       // error, binary unsupported
    2154         w = 0${\color{red}\LstBasicStyle{'}}$233|_lb|;          // quote separator
    2155         w = 0x9b|_kg|;
    2156         w = 5.5d|_st| + 8|_kg| + 25.01|_lb| + heavy;
    2157 }
     2020\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
     2021\begin{cfa}
     202220_hh     // signed char
     202321_hhu   // unsigned char
     202422_h      // signed short int
     202523_uh    // unsigned short int
     202624z        // size_t
     2027\end{cfa}
     2028&
     2029\begin{cfa}
     203020_L8     // int8_t
     203121_ul8    // uint8_t
     203222_l16    // int16_t
     203323_ul16  // uint16_t
     203424_l32    // int32_t
     2035\end{cfa}
     2036&
     2037\begin{cfa}
     203825_ul32      // uint32_t
     203926_l64        // int64_t
     204027_l64u      // uint64_t
     204126_L128     // int128
     204227_L128u  // unsigned int128
    21582043\end{cfa}
    21592044\end{tabular}
    21602045\lstMakeShortInline@%
    2161 \caption{User Literal}
    2162 \label{f:UserLiteral}
    2163 \end{figure}
     2046\end{cquote}
     2047
     2048
     2049\subsection{Units}
     2050
     2051Alternative call syntax (literal argument before routine name) to convert basic literals into user literals.
     2052
     2053{\lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
     2054\begin{cfa}
     2055struct Weight { double stones; };
     2056void ?{}( Weight & w ) { w.stones = 0; }        $\C{// operations}$
     2057void ?{}( Weight & w, double w ) { w.stones = w; }
     2058Weight ?+?( Weight l, Weight r ) { return (Weight){ l.stones + r.stones }; }
     2059
     2060Weight |?`st|( double w ) { return (Weight){ w }; } $\C{// backquote for units}$
     2061Weight |?`lb|( double w ) { return (Weight){ w / 14.0 }; }
     2062Weight |?`kg|( double w ) { return (Weight) { w * 0.1575}; }
     2063
     2064int main() {
     2065        Weight w, heavy = { 20 };                               $\C{// 20 stone}$
     2066        w = 155|`lb|;
     2067        w = 0x_9b_u|`lb|;                                               $\C{// hexadecimal unsigned weight (155)}$
     2068        w = 0_233|`lb|;                                                 $\C{// octal weight (155)}$
     2069        w = 5|`st| + 8|`kg| + 25|`lb| + heavy;
     2070}
     2071\end{cfa}
     2072}%
    21642073
    21652074
     
    21712080In many cases, the interface is an inline wrapper providing overloading during compilation but zero cost at runtime.
    21722081The following sections give a glimpse of the interface reduction to many C libraries.
    2173 In many cases, @signed@/@unsigned@ @char@, @short@, and @_Complex@ functions are available (but not shown) to ensure expression computations remain in a single type, as conversions can distort results.
     2082In many cases, @signed@/@unsigned@ @char@, @short@, and @_Complex@ routines are available (but not shown) to ensure expression computations remain in a single type, as conversions can distort results.
    21742083
    21752084
     
    21992108\begin{cquote}
    22002109\lstDeleteShortInline@%
    2201 \lstset{basicstyle=\linespread{0.9}\sf\small}
    2202 \begin{tabular}{@{}l@{\hspace{0.5\parindentlnth}}l@{}}
    2203 \multicolumn{1}{c@{\hspace{0.5\parindentlnth}}}{\textbf{\CFA}}  & \multicolumn{1}{c}{\textbf{C}}        \\
     2110\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
     2111\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
    22042112\begin{cfa}
    22052113MIN
     2114
    22062115MAX
     2116
    22072117PI
    22082118E
     
    22102120&
    22112121\begin{cfa}
    2212 SCHAR_MIN, CHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN, LLONG_MIN, FLT_MIN, DBL_MIN, LDBL_MIN
    2213 SCHAR_MAX, UCHAR_MAX, SHRT_MAX, INT_MAX, LONG_MAX, LLONG_MAX, FLT_MAX, DBL_MAX, LDBL_MAX
     2122SCHAR_MIN, CHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN, LLONG_MIN,
     2123                FLT_MIN, DBL_MIN, LDBL_MIN
     2124SCHAR_MAX, UCHAR_MAX, SHRT_MAX, INT_MAX, LONG_MAX, LLONG_MAX,
     2125                 FLT_MAX, DBL_MAX, LDBL_MAX
    22142126M_PI, M_PIl
    22152127M_E, M_El
     
    22222134\subsection{Math}
    22232135
    2224 C library @math.h@ provides many mathematical functions.
    2225 \CFA function overloading is used to condense these mathematical functions, \eg:
     2136C library @math.h@ provides many mathematical routines.
     2137\CFA routine overloading is used to condense these mathematical routines, \eg:
    22262138\begin{cquote}
    22272139\lstDeleteShortInline@%
     
    22422154\lstMakeShortInline@%
    22432155\end{cquote}
    2244 The result is a significant reduction in names to access math functions, \eg:
     2156The result is a significant reduction in names to access math routines, \eg:
    22452157\begin{cquote}
    22462158\lstDeleteShortInline@%
     
    22612173\lstMakeShortInline@%
    22622174\end{cquote}
    2263 While \Celeven has type-generic math~\cite[\S~7.25]{C11} in @tgmath.h@ to provide a similar mechanism, these macros are limited, matching a function name with a single set of floating type(s).
     2175While \Celeven has type-generic math~\cite[\S~7.25]{C11} in @tgmath.h@ to provide a similar mechanism, these macros are limited, matching a routine name with a single set of floating type(s).
    22642176For example, it is impossible to overload @atan@ for both one and two arguments;
    22652177instead the names @atan@ and @atan2@ are required (see Section~\ref{s:NameOverloading}).
    2266 The key observation is that only a restricted set of type-generic macros are provided for a limited set of function names, which do not generalize across the type system, as in \CFA.
     2178The key observation is that only a restricted set of type-generic macros are provided for a limited set of routine names, which do not generalize across the type system, as in \CFA.
    22672179
    22682180
    22692181\subsection{Standard}
    22702182
    2271 C library @stdlib.h@ provides many general functions.
    2272 \CFA function overloading is used to condense these utility functions, \eg:
     2183C library @stdlib.h@ provides many general routines.
     2184\CFA routine overloading is used to condense these utility routines, \eg:
    22732185\begin{cquote}
    22742186\lstDeleteShortInline@%
     
    22892201\lstMakeShortInline@%
    22902202\end{cquote}
    2291 The result is a significant reduction in names to access utility functions, \eg:
     2203The result is a significant reduction in names to access utility routines, \eg:
    22922204\begin{cquote}
    22932205\lstDeleteShortInline@%
     
    23082220\lstMakeShortInline@%
    23092221\end{cquote}
    2310 In additon, there are polymorphic functions, like @min@ and @max@, which work on any type with operators @?<?@ or @?>?@.
     2222In additon, there are polymorphic routines, like @min@ and @max@, which work on any type with operators @?<?@ or @?>?@.
    23112223
    23122224The following shows one example where \CFA \emph{extends} an existing standard C interface to reduce complexity and provide safety.
     
    23142226\begin{description}[topsep=3pt,itemsep=2pt,parsep=0pt]
    23152227\item[fill]
    2316 an allocation with a specified character.
     2228after allocation the storage is filled with a specified character.
    23172229\item[resize]
    2318 an existing allocation to decreased or increased its size.
     2230an existing allocation is decreased or increased in size.
    23192231In either case, new storage may or may not be allocated and, if there is a new allocation, as much data from the existing allocation is copied.
    23202232For an increase in storage size, new storage after the copied data may be filled.
    23212233\item[alignment]
    2322 an allocation on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes.
     2234an allocation starts on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes.
    23232235\item[array]
    2324 allocation of the specified number of elements.
     2236the allocation size is scaled to the specified number of array elements.
    23252237An array may be filled, resized, or aligned.
    23262238\end{description}
    2327 Table~\ref{t:StorageManagementOperations} shows the capabilities provided by C/\Celeven allocation-functions and how all the capabilities can be combined into two \CFA functions.
    2328 \CFA storage-management functions extend the C equivalents by overloading, providing shallow type-safety, and removing the need to specify the base allocation-size.
    2329 Figure~\ref{f:StorageAllocation} contrasts \CFA and C storage-allocation performing the same operations with the same type safety.
     2239Table~\ref{t:StorageManagementOperations} shows the capabilities provided by C/\Celeven allocation-routines and how all the capabilities can be combined into two \CFA routines.
     2240
     2241\CFA storage-management routines extend the C equivalents by overloading, providing shallow type-safety, and removing the need to specify the base allocation-size.
     2242The following example contrasts \CFA and C storage-allocation operation performing the same operations with the same type safety:
     2243\begin{cquote}
     2244\begin{cfa}[aboveskip=0pt]
     2245size_t  dim = 10;                                                       $\C{// array dimension}$
     2246char fill = '\xff';                                                     $\C{// initialization fill value}$
     2247int * ip;
     2248\end{cfa}
     2249\lstDeleteShortInline@%
     2250\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
     2251\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
     2252\begin{cfa}
     2253ip = alloc();
     2254ip = alloc( fill );
     2255ip = alloc( dim );
     2256ip = alloc( dim, fill );
     2257ip = alloc( ip, 2 * dim );
     2258ip = alloc( ip, 4 * dim, fill );
     2259
     2260ip = align_alloc( 16 );
     2261ip = align_alloc( 16, fill );
     2262ip = align_alloc( 16, dim );
     2263ip = align_alloc( 16, dim, fill );
     2264\end{cfa}
     2265&
     2266\begin{cfa}
     2267ip = (int *)malloc( sizeof( int ) );
     2268ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, sizeof( int ) );
     2269ip = (int *)malloc( dim * sizeof( int ) );
     2270ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
     2271ip = (int *)realloc( ip, 2 * dim * sizeof( int ) );
     2272ip = (int *)realloc( ip, 4 * dim * sizeof( int ) ); memset( ip, fill, 4 * dim * sizeof( int ) );
     2273
     2274ip = memalign( 16, sizeof( int ) );
     2275ip = memalign( 16, sizeof( int ) ); memset( ip, fill, sizeof( int ) );
     2276ip = memalign( 16, dim * sizeof( int ) );
     2277ip = memalign( 16, dim * sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
     2278\end{cfa}
     2279\end{tabular}
     2280\lstMakeShortInline@%
     2281\end{cquote}
     2282Variadic @new@ (see Section~\ref{sec:variadic-tuples}) cannot support the same overloading because extra parameters are for initialization.
     2283Hence, there are @new@ and @anew@ routines for single and array variables, and the fill value is the arguments to the constructor, \eg:
     2284\begin{cfa}
     2285struct S { int i, j; };
     2286void ?{}( S & s, int i, int j ) { s.i = i; s.j = j; }
     2287S * s = new( 2, 3 );                                            $\C{// allocate storage and run constructor}$
     2288S * as = anew( dim, 2, 3 );                                     $\C{// each array element initialized to 2, 3}$
     2289\end{cfa}
     2290Note, \CC can only initialization array elements via the default constructor.
     2291
     2292Finally, the \CFA memory-allocator has \newterm{sticky properties} for dynamic storage: fill and alignment are remembered with an object's storage in the heap.
     2293When a @realloc@ is performed, the sticky properties are respected, so that new storage is correctly aligned and initialized with the fill character.
    23302294
    23312295\begin{table}
     
    23532317\end{table}
    23542318
    2355 \begin{figure}
    2356 \centering
    2357 \begin{cquote}
    2358 \begin{cfa}[aboveskip=0pt]
    2359 size_t  dim = 10;                                                       $\C{// array dimension}$
    2360 char fill = '\xff';                                                     $\C{// initialization fill value}$
    2361 int * ip;
    2362 \end{cfa}
    2363 \lstDeleteShortInline@%
    2364 \begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
    2365 \multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
    2366 \begin{cfa}
    2367 ip = alloc();
    2368 ip = alloc( fill );
    2369 ip = alloc( dim );
    2370 ip = alloc( dim, fill );
    2371 ip = alloc( ip, 2 * dim );
    2372 ip = alloc( ip, 4 * dim, fill );
    2373 
    2374 ip = align_alloc( 16 );
    2375 ip = align_alloc( 16, fill );
    2376 ip = align_alloc( 16, dim );
    2377 ip = align_alloc( 16, dim, fill );
    2378 \end{cfa}
    2379 &
    2380 \begin{cfa}
    2381 ip = (int *)malloc( sizeof( int ) );
    2382 ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, sizeof( int ) );
    2383 ip = (int *)malloc( dim * sizeof( int ) );
    2384 ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
    2385 ip = (int *)realloc( ip, 2 * dim * sizeof( int ) );
    2386 ip = (int *)realloc( ip, 4 * dim * sizeof( int ) ); memset( ip, fill, 4 * dim * sizeof( int ) );
    2387 
    2388 ip = memalign( 16, sizeof( int ) );
    2389 ip = memalign( 16, sizeof( int ) ); memset( ip, fill, sizeof( int ) );
    2390 ip = memalign( 16, dim * sizeof( int ) );
    2391 ip = memalign( 16, dim * sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
    2392 \end{cfa}
    2393 \end{tabular}
    2394 \lstMakeShortInline@%
    2395 \end{cquote}
    2396 \caption{\CFA versus C Storage-Allocation}
    2397 \label{f:StorageAllocation}
    2398 \end{figure}
    2399 
    2400 Variadic @new@ (see Section~\ref{sec:variadic-tuples}) cannot support the same overloading because extra parameters are for initialization.
    2401 Hence, there are @new@ and @anew@ functions for single and array variables, and the fill value is the arguments to the constructor, \eg:
    2402 \begin{cfa}
    2403 struct S { int i, j; };
    2404 void ?{}( S & s, int i, int j ) { s.i = i; s.j = j; }
    2405 S * s = new( 2, 3 );                                            $\C{// allocate storage and run constructor}$
    2406 S * as = anew( dim, 2, 3 );                                     $\C{// each array element initialized to 2, 3}$
    2407 \end{cfa}
    2408 Note, \CC can only initialization array elements via the default constructor.
    2409 
    2410 Finally, the \CFA memory-allocator has \newterm{sticky properties} for dynamic storage: fill and alignment are remembered with an object's storage in the heap.
    2411 When a @realloc@ is performed, the sticky properties are respected, so that new storage is correctly aligned and initialized with the fill character.
    2412 
    24132319
    24142320\subsection{I/O}
     
    24702376\end{cfa}
    24712377\\
     2378\textbf{output:}
    24722379&
    24732380\begin{cfa}[showspaces=true,aboveskip=0pt]
     
    24972404}%
    24982405\end{itemize}
    2499 There are functions to set and get the separator string, and manipulators to toggle separation on and off in the middle of output.
     2406There are routines to set and get the separator string, and manipulators to toggle separation on and off in the middle of output.
    25002407
    25012408
     
    25042411
    25052412\CFA has an interface to the GMP multi-precision signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP.
    2506 The \CFA interface wraps GMP functions into operator functions to make programming with multi-precision integers identical to using fixed-sized integers.
     2413The \CFA interface wraps GMP routines into operator routines to make programming with multi-precision integers identical to using fixed-sized integers.
    25072414The \CFA type name for multi-precision signed-integers is @Int@ and the header file is @gmp@.
    25082415The following multi-precision factorial programs contrast using GMP with the \CFA and C interfaces.
     
    25492456Since all these languages share a subset essentially comprising standard C, maximal-performance benchmarks would show little runtime variance, other than in length and clarity of source code.
    25502457A more illustrative benchmark measures the costs of idiomatic usage of each language's features.
    2551 Figure~\ref{fig:BenchmarkTest} shows the \CFA benchmark tests for a generic stack based on a singly linked-list, a generic pair-data-structure, and a variadic @print@ function similar to that in Section~\ref{sec:variadic-tuples}.
     2458Figure~\ref{fig:BenchmarkTest} shows the \CFA benchmark tests for a generic stack based on a singly linked-list, a generic pair-data-structure, and a variadic @print@ routine similar to that in Section~\ref{sec:variadic-tuples}.
    25522459The benchmark test is similar for C and \CC.
    25532460The experiment uses element types @int@ and @pair(_Bool, char)@, and pushes $N=40M$ elements on a generic stack, copies the stack, clears one of the stacks, finds the maximum value in the other stack, and prints $N/2$ (to reduce graph height) constants.
     
    25562463\begin{cfa}[xleftmargin=3\parindentlnth,aboveskip=0pt,belowskip=0pt]
    25572464int main( int argc, char * argv[] ) {
     2465        ofstream out = { "cfa-out.txt" };
    25582466        int max = 0, val = 42;
    2559         stack( int ) si, ti;
     2467        stack( int ) si, t;
    25602468
    25612469        REPEAT_TIMED( "push_int", N, push( si, val ); )
    2562         TIMED( "copy_int", ti = si; )
     2470        TIMED( "copy_int", t = si; )
    25632471        TIMED( "clear_int", clear( si ); )
    2564         REPEAT_TIMED( "pop_int", N,
    2565                 int x = pop( ti ); if ( x > max ) max = x; )
     2472        REPEAT_TIMED( "pop_int", N, int x = pop( t ); max = max( x, max ); )
     2473        REPEAT_TIMED( "print_int", N/2, out | val | ':' | val | endl; )
    25662474
    25672475        pair( _Bool, char ) max = { (_Bool)0, '\0' }, val = { (_Bool)1, 'a' };
    2568         stack( pair( _Bool, char ) ) sp, tp;
    2569 
    2570         REPEAT_TIMED( "push_pair", N, push( sp, val ); )
    2571         TIMED( "copy_pair", tp = sp; )
    2572         TIMED( "clear_pair", clear( sp ); )
    2573         REPEAT_TIMED( "pop_pair", N,
    2574                 pair(_Bool, char) x = pop( tp ); if ( x > max ) max = x; )
     2476        stack( pair( _Bool, char ) ) s, t;
     2477
     2478        REPEAT_TIMED( "push_pair", N, push( s, val ); )
     2479        TIMED( "copy_pair", t = s; )
     2480        TIMED( "clear_pair", clear( s ); )
     2481        REPEAT_TIMED( "pop_pair", N, pair(_Bool, char) x = pop( t ); max = max( x, max ); )
     2482        REPEAT_TIMED( "print_pair", N/2, out | val | ':' | val | endl; )
    25752483}
    25762484\end{cfa}
     
    26432551\CC is the most similar language to \CFA;
    26442552both are extensions to C with source and runtime backwards compatibility.
    2645 The fundamental difference is the engineering approach to maintain C compatibility and programmer expectation.
    2646 While \CC provides good compatibility with C, it has a steep learning curve for many of its extensions.
     2553The fundamental difference is in their engineering approach to C compatibility and programmer expectation.
     2554While \CC provides good backwards compatibility with C, it has a steep learning curve for many of its extensions.
    26472555For example, polymorphism is provided via three disjoint mechanisms: overloading, inheritance, and templates.
    26482556The overloading is restricted because resolution does not use the return type, inheritance requires learning object-oriented programming and coping with a restricted nominal-inheritance hierarchy, templates cannot be separately compiled resulting in compilation/code bloat and poor error messages, and determining how these mechanisms interact and which to use is confusing.
    26492557In contrast, \CFA has a single facility for polymorphic code supporting type-safe separate-compilation of polymorphic functions and generic (opaque) types, which uniformly leverage the C procedural paradigm.
    2650 The key mechanism to support separate compilation is \CFA's \emph{explicit} use of assumed type properties.
    2651 Until \CC concepts~\cite{C++Concepts} are standardized (anticipated for \CCtwenty), \CC provides no way to specify the requirements of a generic function beyond compilation errors during template expansion;
     2558The key mechanism to support separate compilation is \CFA's \emph{explicit} use of assumed properties for a type.
     2559Until \CC concepts~\cite{C++Concepts} are standardized (anticipated for \CCtwenty), \CC provides no way to specify the requirements of a generic function in code beyond compilation errors during template expansion;
    26522560furthermore, \CC concepts are restricted to template polymorphism.
    26532561
     
    27002608
    27012609
    2702 \subsection{Control Structures / Declarations / Literals}
    2703 
    2704 Java has default fall through like C/\CC.
    2705 Pascal/Ada/Go/Rust do not have default fall through.
    2706 \Csharp does not have fall through but still requires a break.
    2707 Python uses dictionary mapping. \\
    2708 \CFA choose is like Rust match.
    2709 
    2710 Java has labelled break/continue. \\
    2711 Languages with and without exception handling.
    2712 
    2713 Alternative C declarations. \\
    2714 Different references \\
    2715 Constructors/destructors
    2716 
    2717 0/1 Literals \\
    2718 user defined: D, Objective-C
    2719 
    27202610\section{Conclusion and Future Work}
    27212611
     
    27232613While other programming languages purport to be a better C, they are in fact new and interesting languages in their own right, but not C extensions.
    27242614The purpose of this paper is to introduce \CFA, and showcase language features that illustrate the \CFA type-system and approaches taken to achieve the goal of evolutionary C extension.
    2725 The contributions are a powerful type-system using parametric polymorphism and overloading, generic types, tuples, advanced control structures, and extended declarations, which all have complex interactions.
     2615The contributions are a powerful type-system using parametric polymorphism and overloading, generic types, and tuples, which all have complex interactions.
    27262616The work is a challenging design, engineering, and implementation exercise.
    27272617On the surface, the project may appear as a rehash of similar mechanisms in \CC.
     
    27302620Finally, we demonstrate that \CFA performance for some idiomatic cases is better than C and close to \CC, showing the design is practically applicable.
    27312621
    2732 There is ongoing work on a wide range of \CFA feature extensions, including arrays with size, user-defined conversions, concurrent primitives, and modules.
     2622There is ongoing work on a wide range of \CFA feature extensions, including arrays with size, exceptions, concurrent primitives, modules, and user-defined conversions.
    27332623(While all examples in the paper compile and run, a public beta-release of \CFA will take another 8--12 months to finalize these additional extensions.)
    27342624In addition, there are interesting future directions for the polymorphism design.
     
    27432633\section{Acknowledgments}
    27442634
    2745 The authors would like to recognize the design assistance of Glen Ditchfield, Richard Bilson, Thierry Delisle, and Andrew Beach on the features described in this paper, and thank Magnus Madsen for feedback in the writing.
    2746 This work is supported through a corporate partnership with Huawei Ltd.\ (\url{http://www.huawei.com}), and Aaron Moss and Peter Buhr are partially funded by the Natural Sciences and Engineering Research Council of Canada.
    2747 
     2635The authors would like to recognize the design assistance of Glen Ditchfield, Richard Bilson, and Thierry Delisle on the features described in this paper, and thank Magnus Madsen for feedback in the writing.
     2636%This work is supported in part by a corporate partnership with \grantsponsor{Huawei}{Huawei Ltd.}{http://www.huawei.com}, and Aaron Moss and Peter Buhr are funded by the \grantsponsor{Natural Sciences and Engineering Research Council} of Canada.
    27482637% the first author's \grantsponsor{NSERC-PGS}{NSERC PGS D}{http://www.nserc-crsng.gc.ca/Students-Etudiants/PG-CS/BellandPostgrad-BelletSuperieures_eng.asp} scholarship.
    27492638
     
    27772666        stack_node(T) ** crnt = &s.head;
    27782667        for ( stack_node(T) * next = t.head; next; next = next->next ) {
    2779                 stack_node(T) * new_node = ((stack_node(T)*)malloc());
    2780                 (*new_node){ next->value }; /***/
    2781                 *crnt = new_node;
     2668                *crnt = malloc(){ next->value };
    27822669                stack_node(T) * acrnt = *crnt;
    27832670                crnt = &acrnt->next;
     
    27942681forall(otype T) _Bool empty( const stack(T) & s ) { return s.head == 0; }
    27952682forall(otype T) void push( stack(T) & s, T value ) {
    2796         stack_node(T) * new_node = ((stack_node(T)*)malloc());
    2797         (*new_node){ value, s.head }; /***/
    2798         s.head = new_node;
     2683        s.head = malloc(){ value, s.head };
    27992684}
    28002685forall(otype T) T pop( stack(T) & s ) {
    28012686        stack_node(T) * n = s.head;
    28022687        s.head = n->next;
    2803         T v = n->value;
    2804         delete( n );
    2805         return v;
     2688        T x = n->value;
     2689        ^n{};
     2690        free( n );
     2691        return x;
    28062692}
    28072693forall(otype T) void clear( stack(T) & s ) {
     
    29592845
    29602846
     2847\begin{comment}
     2848\subsubsection{bench.h}
     2849(\texttt{bench.hpp} is similar.)
     2850
     2851\lstinputlisting{evaluation/bench.h}
     2852
     2853\subsection{C}
     2854
     2855\subsubsection{c-stack.h} ~
     2856
     2857\lstinputlisting{evaluation/c-stack.h}
     2858
     2859\subsubsection{c-stack.c} ~
     2860
     2861\lstinputlisting{evaluation/c-stack.c}
     2862
     2863\subsubsection{c-pair.h} ~
     2864
     2865\lstinputlisting{evaluation/c-pair.h}
     2866
     2867\subsubsection{c-pair.c} ~
     2868
     2869\lstinputlisting{evaluation/c-pair.c}
     2870
     2871\subsubsection{c-print.h} ~
     2872
     2873\lstinputlisting{evaluation/c-print.h}
     2874
     2875\subsubsection{c-print.c} ~
     2876
     2877\lstinputlisting{evaluation/c-print.c}
     2878
     2879\subsubsection{c-bench.c} ~
     2880
     2881\lstinputlisting{evaluation/c-bench.c}
     2882
     2883\subsection{\CFA}
     2884
     2885\subsubsection{cfa-stack.h} ~
     2886
     2887\lstinputlisting{evaluation/cfa-stack.h}
     2888
     2889\subsubsection{cfa-stack.c} ~
     2890
     2891\lstinputlisting{evaluation/cfa-stack.c}
     2892
     2893\subsubsection{cfa-print.h} ~
     2894
     2895\lstinputlisting{evaluation/cfa-print.h}
     2896
     2897\subsubsection{cfa-print.c} ~
     2898
     2899\lstinputlisting{evaluation/cfa-print.c}
     2900
     2901\subsubsection{cfa-bench.c} ~
     2902
     2903\lstinputlisting{evaluation/cfa-bench.c}
     2904
     2905\subsection{\CC}
     2906
     2907\subsubsection{cpp-stack.hpp} ~
     2908
     2909\lstinputlisting[language=c++]{evaluation/cpp-stack.hpp}
     2910
     2911\subsubsection{cpp-print.hpp} ~
     2912
     2913\lstinputlisting[language=c++]{evaluation/cpp-print.hpp}
     2914
     2915\subsubsection{cpp-bench.cpp} ~
     2916
     2917\lstinputlisting[language=c++]{evaluation/cpp-bench.cpp}
     2918
     2919\subsection{\CCV}
     2920
     2921\subsubsection{object.hpp} ~
     2922
     2923\lstinputlisting[language=c++]{evaluation/object.hpp}
     2924
     2925\subsubsection{cpp-vstack.hpp} ~
     2926
     2927\lstinputlisting[language=c++]{evaluation/cpp-vstack.hpp}
     2928
     2929\subsubsection{cpp-vstack.cpp} ~
     2930
     2931\lstinputlisting[language=c++]{evaluation/cpp-vstack.cpp}
     2932
     2933\subsubsection{cpp-vprint.hpp} ~
     2934
     2935\lstinputlisting[language=c++]{evaluation/cpp-vprint.hpp}
     2936
     2937\subsubsection{cpp-vbench.cpp} ~
     2938
     2939\lstinputlisting[language=c++]{evaluation/cpp-vbench.cpp}
     2940\end{comment}
     2941
    29612942\end{document}
    29622943
Note: See TracChangeset for help on using the changeset viewer.