Ignore:
File:
1 edited

Legend:

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

    rd16f9fd r4137e31  
    11\documentclass[AMA,STIX1COL]{WileyNJD-v2}
    2 \setlength\typewidth{170mm}
    3 \setlength\textwidth{170mm}
    42
    53\articletype{RESEARCH ARTICLE}%
    64
    7 \received{12 March 2018}
    8 \revised{8 May 2018}
    9 \accepted{28 June 2018}
    10 
    11 \setlength\typewidth{168mm}
    12 \setlength\textwidth{168mm}
     5\received{26 April 2016}
     6\revised{6 June 2016}
     7\accepted{6 June 2016}
     8
    139\raggedbottom
    1410
     
    191187}
    192188
    193 \title{\texorpdfstring{\protect\CFA : Adding modern programming language features to C}{Cforall : Adding modern programming language features to C}}
     189\title{\texorpdfstring{\protect\CFA : Adding Modern Programming Language Features to C}{Cforall : Adding Modern Programming Language Features to C}}
    194190
    195191\author[1]{Aaron Moss}
    196192\author[1]{Robert Schluntz}
    197 \author[1]{Peter A. Buhr}
    198 \author[]{\textcolor{blue}{Q1 AUTHOR NAMES CORRECT}}
     193\author[1]{Peter A. Buhr*}
    199194\authormark{MOSS \textsc{et al}}
    200195
    201 \address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, Ontario}, \country{Canada}}}
    202 
    203 \corres{Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}
     196\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
     197
     198\corres{*Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON, N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}
    204199
    205200\fundingInfo{Natural Sciences and Engineering Research Council of Canada}
    206201
    207202\abstract[Summary]{
    208 The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from hobby projects to commercial operating systems.
    209 This installation base and the programmers producing it represent a massive software engineering investment spanning decades and likely to continue for decades more.
    210 Nevertheless, C, which was first standardized almost 30 \textcolor{blue}{CHANGE ``40'' TO ``30''} years ago, lacks many features that make programming in more modern languages safer and more productive.
    211 The goal of the \CFA project (pronounced ``C for all'') is to create an extension of C that provides modern safety and productivity features while still ensuring strong backward compatibility with C and its programmers.
    212 Prior projects have attempted similar goals but failed to honor the C programming style;
    213 for instance, adding object-oriented or functional programming with garbage collection is a nonstarter for many C developers.
    214 Specifically, \CFA is designed to have an orthogonal feature set based closely on the C programming paradigm, so that \CFA features can be added \emph{incrementally} to existing C code bases, and C programmers can learn \CFA extensions on an as-needed basis, preserving investment in existing code and programmers.
    215 This paper presents a quick tour of \CFA features, showing how their design avoids shortcomings of similar features in C and other C-like languages.
     203The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from hobby projects to commercial operating-systems.
     204This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
     205Nevertheless, C, first standardized almost thirty years ago, lacks many features that make programming in more modern languages safer and more productive.
     206
     207The goal of the \CFA project (pronounced ``C-for-all'') is to create an extension of C that provides modern safety and productivity features while still ensuring strong backwards compatibility with C and its programmers.
     208Prior projects have attempted similar goals but failed to honour C programming-style;
     209for instance, adding object-oriented or functional programming with garbage collection is a non-starter for many C developers.
     210Specifically, \CFA is designed to have an orthogonal feature-set based closely on the C programming paradigm, so that \CFA features can be added \emph{incrementally} to existing C code-bases, and C programmers can learn \CFA extensions on an as-needed basis, preserving investment in existing code and programmers.
     211This paper presents a quick tour of \CFA features showing how their design avoids shortcomings of similar features in C and other C-like languages.
    216212Experimental results are presented to validate several of the new features.
    217213}%
    218214
    219 \keywords{C, Cforall, generic types, polymorphic functions, tuple types, variadic types}
     215\keywords{generic types, tuple types, variadic types, polymorphic functions, C, Cforall}
    220216
    221217
    222218\begin{document}
    223 %\linenumbers                                            % comment out to turn off line numbering
     219\linenumbers                                            % comment out to turn off line numbering
    224220
    225221\maketitle
     
    228224\section{Introduction}
    229225
    230 The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from hobby projects to commercial operating systems.
    231 This installation base and the programmers producing it represent a massive software engineering investment spanning decades and likely to continue for decades more.
    232 The TIOBE index~\cite{TIOBE} \textcolor{blue}{CHANGE ``TIOBE'' TO ``The TIOBE index''} ranks the top five most \emph{popular} programming languages as Java 15\%, \Textbf{C 12\%}, \Textbf{\CC 5.5\%}, and Python 5\%, \Csharp 4.5\% = 42\%, where the next 50 languages are less than 4\% each with a long tail.
    233 The top three rankings over the past 30 years are as follows.
    234 \newpage
    235 \textcolor{blue}{MOVE TABLE HERE}
     226The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from hobby projects to commercial operating-systems.
     227This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
     228The TIOBE index~\cite{TIOBE} ranks the top 5 most \emph{popular} programming languages as: Java 15\%, \Textbf{C 12\%}, \Textbf{\CC 5.5\%}, Python 5\%, \Csharp 4.5\% = 42\%, where the next 50 languages are less than 4\% each, with a long tail.
     229The top 3 rankings over the past 30 years are:
    236230\begin{center}
    237231\setlength{\tabcolsep}{10pt}
    238 \fontsize{9bp}{11bp}\selectfont
    239 \lstDeleteShortInline@%
    240 \begin{tabular}{@{}cccccccc@{}}
    241                 & 2018  & 2013  & 2008  & 2003  & 1998  & 1993  & 1988  \\
    242 Java    & 1             & 2             & 1             & 1             & 18    & --    & --    \\
     232\lstDeleteShortInline@%
     233\begin{tabular}{@{}rccccccc@{}}
     234                & 2018  & 2013  & 2008  & 2003  & 1998  & 1993  & 1988  \\ \hline
     235Java    & 1             & 2             & 1             & 1             & 18    & -             & -             \\
    243236\Textbf{C}& \Textbf{2} & \Textbf{1} & \Textbf{2} & \Textbf{2} & \Textbf{1} & \Textbf{1} & \Textbf{1} \\
    244237\CC             & 3             & 4             & 3             & 3             & 2             & 2             & 5             \\
     
    246239\lstMakeShortInline@%
    247240\end{center}
    248 
    249241Love it or hate it, C is extremely popular, highly used, and one of the few systems languages.
    250242In many cases, \CC is often used solely as a better C.
    251 Nevertheless, C, which was first standardized almost 30 \textcolor{blue}{CHANGE ``40'' TO ``30''} years ago~\cite{ANSI89:C}, lacks many features that make programming in more modern languages safer and more productive.
    252 
    253 \CFA (pronounced ``C for all'' and written \CFA or Cforall) is an evolutionary extension of the C programming language that adds modern language features to C, while maintaining source and runtime compatibility in the familiar C programming model.
    254 The four key design goals for \CFA~\cite{Bilson03} are as follows:
    255 (1) the behavior of standard C code must remain the same when translated by a \CFA compiler as when translated by a C compiler;
    256 (2) the standard C code must be as fast and as small when translated by a \CFA compiler as when translated by a C compiler;
    257 (3) the \CFA code must be at least as portable as standard C code;
    258 (4) extensions introduced by \CFA must be translated in the most efficient way possible.
    259 These goals ensure that the existing C code bases can be converted into \CFA incrementally with minimal effort, and C programmers can productively generate \CFA code without training beyond the features being used.
    260 \CC is used similarly but has the disadvantages of multiple legacy design choices that cannot be updated and active divergence of the language model from C, requiring significant effort and training to incrementally add \CC to a C-based project.
    261 
    262 All language features discussed in this paper are working, except some advanced exception-handling features.
    263 Not discussed in this paper are the integrated concurrency constructs and user-level threading library~\cite{Delisle18}.
     243Nevertheless, C, first standardized almost forty years ago~\cite{ANSI89:C}, lacks many features that make programming in more modern languages safer and more productive.
     244
     245\CFA (pronounced ``C-for-all'', and written \CFA or Cforall) is an evolutionary extension of the C programming language that adds modern language-features to C, while maintaining source and runtime compatibility in the familiar C programming model.
     246The four key design goals for \CFA~\cite{Bilson03} are:
     247(1) The behaviour of standard C code must remain the same when translated by a \CFA compiler as when translated by a C compiler;
     248(2) Standard C code must be as fast and as small when translated by a \CFA compiler as when translated by a C compiler;
     249(3) \CFA code must be at least as portable as standard C code;
     250(4) Extensions introduced by \CFA must be translated in the most efficient way possible.
     251These goals ensure existing C code-bases can be converted to \CFA incrementally with minimal effort, and C programmers can productively generate \CFA code without training beyond the features being used.
     252\CC is used similarly, but has the disadvantages of multiple legacy design-choices that cannot be updated, and active divergence of the language model from C, requiring significant effort and training to incrementally add \CC to a C-based project.
     253
     254All languages features discussed in this paper are working, except some advanced exception-handling features.
     255Not discussed in this paper are the integrated concurrency-constructs and user-level threading-library~\cite{Delisle18}.
    264256\CFA is an \emph{open-source} project implemented as a source-to-source translator from \CFA to the gcc-dialect of C~\cite{GCCExtensions}, allowing it to leverage the portability and code optimizations provided by gcc, meeting goals (1)--(3).
    265257% @plg2[9]% cd cfa-cc/src; cloc ArgTweak CodeGen CodeTools Common Concurrency ControlStruct Designators GenPoly InitTweak MakeLibCfa.cc MakeLibCfa.h Parser ResolvExpr SymTab SynTree Tuples driver prelude main.cc
     
    277269% SUM:                           223           8203           8263          46479
    278270% -------------------------------------------------------------------------------
    279 The \CFA translator is 200+ files and 46\,000+ lines of code written in C/\CC.
    280 A translator versus a compiler makes it easier and faster to generate and debug the C object code rather than the intermediate, assembler, or machine code;
     271The \CFA translator is 200+ files and 46,000+ lines of code written in C/\CC.
     272A translator versus a compiler makes it easier and faster to generate and debug C object-code rather than intermediate, assembler or machine code;
    281273ultimately, a compiler is necessary for advanced features and optimal performance.
    282274% The translator design is based on the \emph{visitor pattern}, allowing multiple passes over the abstract code-tree, which works well for incrementally adding new feature through additional visitor passes.
    283275Two key translator components are expression analysis, determining expression validity and what operations are required for its implementation, and code generation, dealing with multiple forms of overloading, polymorphism, and multiple return values by converting them into C code for a C compiler that supports none of these features.
    284 Details of these components are available in chapters 2 and 3 in the work of Bilson~\cite{Bilson03} and form the base for the current \CFA translator.
     276Details of these components are available in Bilson~\cite{Bilson03} Chapters 2 and 3, and form the base for the current \CFA translator.
    285277% @plg2[8]% cd cfa-cc/src; cloc libcfa
    286278% -------------------------------------------------------------------------------
     
    297289% SUM:                           100           1895           2785          11763
    298290% -------------------------------------------------------------------------------
    299 The \CFA runtime system is 100+ files and 11\,000+ lines of code, written in \CFA.
     291The \CFA runtime system is 100+ files and 11,000+ lines of code, written in \CFA.
    300292Currently, the \CFA runtime is the largest \emph{user} of \CFA providing a vehicle to test the language features and implementation.
    301293% @plg2[6]% cd cfa-cc/src; cloc tests examples benchmark
     
    324316
    325317
    326 \vspace*{-6pt}
    327318\section{Polymorphic Functions}
    328319
    329 \CFA introduces both ad hoc and parametric polymorphism to C, with a design originally formalized by Ditchfield~\cite{Ditchfield92} and first implemented by Bilson~\cite{Bilson03}.
    330 Shortcomings are identified in the existing approaches to generic and variadic data types in C-like languages and how these shortcomings are avoided in \CFA.
    331 Specifically, the solution is both reusable and type checked, as well as conforming to the design goals of \CFA with ergonomic use of existing C abstractions.
     320\CFA introduces both ad-hoc and parametric polymorphism to C, with a design originally formalized by Ditchfield~\cite{Ditchfield92}, and first implemented by Bilson~\cite{Bilson03}.
     321Shortcomings are identified in existing approaches to generic and variadic data types in C-like languages and how these shortcomings are avoided in \CFA.
     322Specifically, the solution is both reusable and type-checked, as well as conforming to the design goals of \CFA with ergonomic use of existing C abstractions.
    332323The new constructs are empirically compared with C and \CC approaches via performance experiments in Section~\ref{sec:eval}.
    333324
    334325
    335 \vspace*{-6pt}
    336 \subsection{Name overloading}
     326\subsection{Name Overloading}
    337327\label{s:NameOverloading}
    338328
    339329\begin{quote}
    340 ``There are only two hard things in Computer Science: cache invalidation and \emph{naming things}.''---Phil Karlton
     330There are only two hard things in Computer Science: cache invalidation and \emph{naming things} -- Phil Karlton
    341331\end{quote}
    342332\vspace{-9pt}
    343 C already has a limited form of ad hoc polymorphism in its basic arithmetic operators, which apply to a variety of different types using identical syntax.
     333C already has a limited form of ad-hoc polymorphism in its basic arithmetic operators, which apply to a variety of different types using identical syntax.
    344334\CFA extends the built-in operator overloading by allowing users to define overloads for any function, not just operators, and even any variable;
    345335Section~\ref{sec:libraries} includes a number of examples of how this overloading simplifies \CFA programming relative to C.
    346336Code generation for these overloaded functions and variables is implemented by the usual approach of mangling the identifier names to include a representation of their type, while \CFA decides which overload to apply based on the same ``usual arithmetic conversions'' used in C to disambiguate operator overloads.
    347 \textcolor{blue}{REMOVE ``We have the following as an example''}
    348 \newpage
    349 \textcolor{blue}{UPDATE FOLLOWING PROGRAM EXAMPLE WITH ADJUSTED COMMENTS TO FIT PAGE WIDTH.}
     337As an example:
    350338\begin{cfa}
    351339int max = 2147483647;                                           $\C[4in]{// (1)}$
     
    353341int max( int a, int b ) { return a < b ? b : a; }  $\C{// (3)}$
    354342double max( double a, double b ) { return a < b ? b : a; }  $\C{// (4)}\CRT$
    355 max( 7, -max );                                         $\C[3in]{// uses (3) and (1), by matching int from constant 7}$
     343max( 7, -max );                                         $\C{// uses (3) and (1), by matching int from constant 7}$
    356344max( max, 3.14 );                                       $\C{// uses (4) and (2), by matching double from constant 3.14}$
    357345max( max, -max );                                       $\C{// ERROR, ambiguous}$
    358 int m = max( max, -max );                       $\C{// uses (3) and (1) twice, by matching return type}\CRT$
     346int m = max( max, -max );                       $\C{// uses (3) and (1) twice, by matching return type}$
    359347\end{cfa}
    360348
     
    365353As 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.
    366354
    367 \Celeven added @_Generic@ expressions (see section~6.5.1.1 of the ISO/IEC 9899~\cite{C11}), which is used with preprocessor macros to provide ad hoc polymorphism;
     355\Celeven added @_Generic@ expressions~\cite[\S~6.5.1.1]{C11}, which is used with preprocessor macros to provide ad-hoc polymorphism;
    368356however, this polymorphism is both functionally and ergonomically inferior to \CFA name overloading.
    369 The macro wrapping the generic expression imposes some limitations, for instance, it cannot implement the example above, because the variables @max@ are ambiguous with the functions @max@.
     357The macro wrapping the generic expression imposes some limitations;
     358\eg, it cannot implement the example above, because the variables @max@ are ambiguous with the functions @max@.
    370359Ergonomic 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.
    371 \CFA supports @_Generic@ expressions for backward compatibility, but it is an unnecessary mechanism.
     360\CFA supports @_Generic@ expressions for backwards compatibility, but it is an unnecessary mechanism. \TODO{actually implement that}
    372361
    373362% http://fanf.livejournal.com/144696.html
     
    376365
    377366
    378 \vspace*{-10pt}
    379 \subsection{\texorpdfstring{\protect\lstinline{forall} functions}{forall functions}}
     367\subsection{\texorpdfstring{\protect\lstinline{forall} Functions}{forall Functions}}
    380368\label{sec:poly-fns}
    381369
    382 The signature feature of \CFA is parametric-polymorphic functions~\cite{forceone:impl,Cormack90,Duggan96} with functions generalized using a @forall@ clause (giving the language its name). \textcolor{blue}{REMOVE ``as follows''}
     370The signature feature of \CFA is parametric-polymorphic functions~\cite{forceone:impl,Cormack90,Duggan96} with functions generalized using a @forall@ clause (giving the language its name):
    383371\begin{cfa}
    384372`forall( otype T )` T identity( T val ) { return val; }
     
    387375This @identity@ function can be applied to any complete \newterm{object type} (or @otype@).
    388376The 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.
    389 The \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.
    390 If this extra information is not needed, for instance, for a pointer, the type parameter can be declared as a \newterm{data type} (or @dtype@).
    391 
    392 In \CFA, the polymorphic runtime cost is spread over each polymorphic call, because more arguments are passed to polymorphic functions;
    393 the experiments in Section~\ref{sec:eval} show this overhead is similar to \CC virtual function calls.
    394 A design advantage is that, unlike \CC template functions, \CFA polymorphic functions are compatible with C \emph{separate compilation}, preventing compilation and code bloat.
    395 
    396 Since bare polymorphic types provide a restricted set of available operations, \CFA provides a \newterm{type assertion}~\cite[pp.~37-44]{Alphard} mechanism to provide further type information, where type assertions may be variable or function declarations that depend on a polymorphic type variable.
    397 For example, the function @twice@ can be defined using the \CFA syntax for operator overloading. \textcolor{blue}{REMOVE ``as follows''}
     377The \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.
     378If this extra information is not needed, \eg for a pointer, the type parameter can be declared as a \newterm{data type} (or @dtype@).
     379
     380In \CFA, the polymorphic runtime-cost is spread over each polymorphic call, because more arguments are passed to polymorphic functions;
     381the experiments in Section~\ref{sec:eval} show this overhead is similar to \CC virtual-function calls.
     382A design advantage is that, unlike \CC template-functions, \CFA polymorphic-functions are compatible with C \emph{separate compilation}, preventing compilation and code bloat.
     383
     384Since bare polymorphic-types provide a restricted set of available operations, \CFA provides a \newterm{type assertion}~\cite[pp.~37-44]{Alphard} mechanism to provide further type information, where type assertions may be variable or function declarations that depend on a polymorphic type-variable.
     385For example, the function @twice@ can be defined using the \CFA syntax for operator overloading:
    398386\begin{cfa}
    399387forall( otype T `| { T ?+?(T, T); }` ) T twice( T x ) { return x `+` x; }  $\C{// ? denotes operands}$
    400388int val = twice( twice( 3.7 ) );  $\C{// val == 14}$
    401389\end{cfa}
    402 This works for any type @T@ with a matching addition operator.
    403 The polymorphism is achieved by creating a wrapper function for calling @+@ with the @T@ bound to @double@ and then passing this function to the first call of @twice@.
    404 There is now the option of using the same @twice@ and converting the result into @int@ on assignment or creating another @twice@ with the type parameter @T@ bound to @int@ because \CFA uses the return type~\cite{Cormack81,Baker82,Ada} in its type analysis.
    405 The first approach has a late conversion from @double@ to @int@ on the final assignment, whereas the second has an early conversion to @int@.
    406 \CFA minimizes the number of conversions and their potential to lose information;
    407 hence, it selects the first approach, which corresponds with C programmer intuition.
     390which works for any type @T@ with a matching addition operator.
     391The 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@.
     392There 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.
     393The first approach has a late conversion from @double@ to @int@ on the final assignment, while the second has an early conversion to @int@.
     394\CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach, which corresponds with C-programmer intuition.
    408395
    409396Crucial to the design of a new programming language are the libraries to access thousands of external software features.
    410 Like \CC, \CFA inherits a massive compatible library base, where other programming languages must rewrite or provide fragile interlanguage communication with C.
    411 A simple example is leveraging the existing type-unsafe (@void *@) C @bsearch@ to binary search a sorted float array. \textcolor{blue}{REMOVE ``as follows''}
     397Like \CC, \CFA inherits a massive compatible library-base, where other programming languages must rewrite or provide fragile inter-language communication with C.
     398A simple example is leveraging the existing type-unsafe (@void *@) C @bsearch@ to binary search a sorted float array:
    412399\begin{cfa}
    413400void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
     
    419406double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp ); $\C{// search sorted array}$
    420407\end{cfa}
    421 This can be augmented simply with generalized, type-safe, \CFA-overloaded wrappers.
     408which can be augmented simply with generalized, type-safe, \CFA-overloaded wrappers:
    422409\begin{cfa}
    423410forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) {
     
    433420\end{cfa}
    434421The nested function @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
    435 % FIX
    436 Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling conventions and template declarations cannot appear in block scope.
    437 In addition, an alternate kind of return is made available: position versus pointer to found element.
    438 \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@.
     422Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
     423As well, an alternate kind of return is made available: position versus pointer to found element.
     424\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@.
    439425
    440426\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}).
     
    446432\end{cfa}
    447433
    448 Call site inferencing and nested functions provide a localized form of inheritance.
     434Call-site inferencing and nested functions provide a localized form of inheritance.
    449435For example, the \CFA @qsort@ only sorts in ascending order using @<@.
    450 However, it is trivial to locally change this behavior.
     436However, it is trivial to locally change this behaviour:
    451437\begin{cfa}
    452438forall( otype T | { int ?<?( T, T ); } ) void qsort( const T * arr, size_t size ) { /* use C qsort */ }
    453439int main() {
    454         int ?<?( double x, double y ) { return x `>` y; } $\C{// locally override behavior}$
     440        int ?<?( double x, double y ) { return x `>` y; } $\C{// locally override behaviour}$
    455441        qsort( vals, 10 );                                                      $\C{// descending sort}$
    456442}
    457443\end{cfa}
    458444The local version of @?<?@ performs @?>?@ overriding the built-in @?<?@ so it is passed to @qsort@.
    459 Therefore, programmers can easily form local environments, adding and modifying appropriate functions, to maximize the reuse of other existing functions and types.
    460 
    461 To reduce duplication, it is possible to distribute a group of @forall@ (and storage-class qualifiers) over functions/types, such that each block declaration is prefixed by the group (see the example in Appendix~\ref{s:CforallStack}).
     445Hence, programmers can easily form local environments, adding and modifying appropriate functions, to maximize reuse of other existing functions and types.
     446
     447To reduce duplication, it is possible to distribute a group of @forall@ (and storage-class qualifiers) over functions/types, so each block declaration is prefixed by the group (see example in Appendix~\ref{s:CforallStack}).
    462448\begin{cfa}
    463449forall( otype `T` ) {                                                   $\C{// distribution block, add forall qualifier to declarations}$
     
    470456
    471457
     458\vspace*{-2pt}
    472459\subsection{Traits}
    473460
    474 \CFA provides \newterm{traits} to name a group of type assertions, where the trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each function declaration.
     461\CFA provides \newterm{traits} to name a group of type assertions, where the trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each function declaration:
     462
    475463\begin{cquote}
    476464\lstDeleteShortInline@%
     
    499487\end{cquote}
    500488
    501 Note that the @sumable@ trait does not include a copy constructor needed for the right side of @?+=?@ and return;
    502 it is provided by @otype@, which is syntactic sugar for the following trait.
     489Note, the @sumable@ trait does not include a copy constructor needed for the right side of @?+=?@ and return;
     490it is provided by @otype@, which is syntactic sugar for the following trait:
    503491\begin{cfa}
    504492trait otype( dtype T | sized(T) ) {  // sized is a pseudo-trait for types with known size and alignment
     
    509497};
    510498\end{cfa}
    511 Given 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.
    512 
    513 In summation, the \CFA type system uses \newterm{nominal typing} for concrete types, matching with the C type system, and \newterm{structural typing} for polymorphic types.
     499Given 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.
     500
     501In summation, the \CFA type-system uses \newterm{nominal typing} for concrete types, matching with the C type-system, and \newterm{structural typing} for polymorphic types.
    514502Hence, trait names play no part in type equivalence;
    515503the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
    516 Nevertheless, trait names form a logical subtype hierarchy with @dtype@ at the top, where traits often contain overlapping assertions, \eg operator @+@.
    517 Traits are used like interfaces in Java or abstract base classes in \CC, but without the nominal inheritance relationships.
    518 Instead, each polymorphic function (or generic type) defines the structural type needed for its execution (polymorphic type key), and this key is fulfilled at each call site from the lexical environment, which is similar to the Go~\cite{Go} interfaces.
    519 Hence, new lexical scopes and nested functions are used extensively to create local subtypes, as in the @qsort@ example, without having to manage a nominal inheritance hierarchy.
     504Nevertheless, trait names form a logical subtype-hierarchy with @dtype@ at the top, where traits often contain overlapping assertions, \eg operator @+@.
     505Traits are used like interfaces in Java or abstract base-classes in \CC, but without the nominal inheritance-relationships.
     506Instead, each polymorphic function (or generic type) defines the structural type needed for its execution (polymorphic type-key), and this key is fulfilled at each call site from the lexical environment, which is similar to Go~\cite{Go} interfaces.
     507Hence, new lexical scopes and nested functions are used extensively to create local subtypes, as in the @qsort@ example, without having to manage a nominal-inheritance hierarchy.
    520508% (Nominal inheritance can be approximated with traits using marker variables or functions, as is done in Go.)
    521509
     
    548536
    549537A significant shortcoming of standard C is the lack of reusable type-safe abstractions for generic data structures and algorithms.
    550 Broadly speaking, there are three approaches to implement abstract data structures in C.
    551 One approach is to write bespoke data structures for each context in which they are needed.
    552 While 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.
    553 A second approach is to use @void *@-based polymorphism, \eg the C standard library functions @bsearch@ and @qsort@, which allow for the reuse of code with common functionality.
    554 However, 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 otherwise not needed.
    555 A 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.
     538Broadly speaking, there are three approaches to implement abstract data-structures in C.
     539One approach is to write bespoke data-structures for each context in which they are needed.
     540While 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.
     541A 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.
     542However, 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.
     543A 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.
    556544Furthermore, writing and using preprocessor macros is unnatural and inflexible.
    557545
    558 \CC, Java, and other languages use \newterm{generic types} to produce type-safe abstract data types.
    559 \CFA generic types integrate efficiently and naturally with the existing polymorphic functions, while retaining backward compatibility with C and providing separate compilation.
     546\CC, Java, and other languages use \newterm{generic types} to produce type-safe abstract data-types.
     547\CFA generic types integrate efficiently and naturally with the existing polymorphic functions, while retaining backwards compatibility with C and providing separate compilation.
    560548However, for known concrete parameters, the generic-type definition can be inlined, like \CC templates.
    561549
    562 A generic type can be declared by placing a @forall@ specifier on a @struct@ or @union@ declaration and instantiated using a parenthesized list of types after the type name.
     550A generic type can be declared by placing a @forall@ specifier on a @struct@ or @union@ declaration, and instantiated using a parenthesized list of types after the type name:
    563551\begin{cquote}
    564552\lstDeleteShortInline@%
     
    588576
    589577\CFA classifies generic types as either \newterm{concrete} or \newterm{dynamic}.
    590 Concrete types have a fixed memory layout regardless of type parameters, whereas dynamic types vary in memory layout depending on their type parameters.
     578Concrete types have a fixed memory layout regardless of type parameters, while dynamic types vary in memory layout depending on their type parameters.
    591579A \newterm{dtype-static} type has polymorphic parameters but is still concrete.
    592580Polymorphic pointers are an example of dtype-static types;
    593 given some type variable @T@, @T@ is a polymorphic type, as is @T *@, but @T *@ has a fixed size and can, therefore, be represented by @void *@ in code generation.
    594 
    595 \CFA generic types also allow checked argument constraints.
    596 For example, the following declaration of a sorted set type ensures the set key supports equality and relational comparison.
     581given some type variable @T@, @T@ is a polymorphic type, as is @T *@, but @T *@ has a fixed size and can therefore be represented by @void *@ in code generation.
     582
     583\CFA generic types also allow checked argument-constraints.
     584For example, the following declaration of a sorted set-type ensures the set key supports equality and relational comparison:
    597585\begin{cfa}
    598586forall( otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); } ) struct sorted_set;
     
    600588
    601589
    602 \subsection{Concrete generic types}
    603 
    604 The \CFA translator template expands concrete generic types into new structure types, affording maximal inlining.
    605 To enable interoperation among equivalent instantiations of a generic type, the translator saves the set of instantiations currently in scope and reuses the generated structure declarations where appropriate.
    606 A function declaration that accepts or returns a concrete generic type produces a declaration for the instantiated structure in the same scope, which all callers may reuse.
    607 For example, the concrete instantiation for @pair( const char *, int )@ is \textcolor{blue}{REMOVE ``as follows.''}
     590\subsection{Concrete Generic-Types}
     591
     592The \CFA translator template-expands concrete generic-types into new structure types, affording maximal inlining.
     593To enable inter-operation among equivalent instantiations of a generic type, the translator saves the set of instantiations currently in scope and reuses the generated structure declarations where appropriate.
     594A function declaration that accepts or returns a concrete generic-type produces a declaration for the instantiated structure in the same scope, which all callers may reuse.
     595For example, the concrete instantiation for @pair( const char *, int )@ is:
    608596\begin{cfa}
    609597struct _pair_conc0 {
     
    612600\end{cfa}
    613601
    614 A concrete generic type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations.
    615 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.
     602A concrete generic-type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations.
     603In 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:
    616604\begin{cfa}
    617605struct _pair_conc1 {
     
    621609
    622610
    623 \subsection{Dynamic generic types}
    624 
    625 Though \CFA implements concrete generic types efficiently, it also has a fully general system for dynamic generic types.
    626 As 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.
    627 Dynamic generic types also have an \newterm{offset array} containing structure-member offsets.
    628 A dynamic generic @union@ needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
    629 Access to members of a dynamic structure is provided at runtime via base displacement addressing
    630 % FIX
    631 using the structure pointer and the member offset (similar to the @offsetof@ macro), moving a compile-time offset calculation to runtime.
     611\subsection{Dynamic Generic-Types}
     612
     613Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types.
     614As 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.
     615Dynamic generic-types also have an \newterm{offset array} containing structure-member offsets.
     616A dynamic generic-@union@ needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
     617Access 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.
    632618
    633619The offset arrays are statically generated where possible.
    634 If a dynamic generic type is declared to be passed or returned by value from a polymorphic function, the translator can safely assume that the generic type is complete (\ie has a known layout) at any call site, and the offset array is passed from the caller;
     620If 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;
    635621if 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.
    636 As an example, the body of the second @value@ function is implemented as \textcolor{blue}{REMOVE ``follows.''}
     622As an example, the body of the second @value@ function is implemented as:
    637623\begin{cfa}
    638624_assign_T( _retval, p + _offsetof_pair[1] ); $\C{// return *p.second}$
    639625\end{cfa}
    640 \newpage
    641 \noindent
    642 \textcolor{blue}{NO PARAGRAPH INDENT} Here, @_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, and @_retval@ is the pointer to a caller-allocated buffer for the return value, the usual \CFA method to handle dynamically sized return types.
    643 @_offsetof_pair@ is the offset array passed into @value@;
    644 this array is generated at the call site as \textcolor{blue}{REMOVE ``follows.''}
     626@_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.
     627@_offsetof_pair@ is the offset array passed into @value@; this array is generated at the call site as:
    645628\begin{cfa}
    646629size_t _offsetof_pair[] = { offsetof( _pair_conc0, first ), offsetof( _pair_conc0, second ) }
    647630\end{cfa}
    648631
    649 In some cases, the offset arrays cannot be statically generated.
    650 For instance, modularity is generally provided in C by including an opaque forward declaration of a structure and associated accessor and mutator functions in a header file, with the actual implementations in a separately compiled @.c@ file.
    651 \CFA supports this pattern for generic types, but the caller does not know the actual layout or size of the dynamic generic type and only holds it by a pointer.
     632In some cases the offset arrays cannot be statically generated.
     633For instance, modularity is generally provided in C by including an opaque forward-declaration of a structure and associated accessor and mutator functions in a header file, with the actual implementations in a separately-compiled @.c@ file.
     634\CFA supports this pattern for generic types, but the caller does not know the actual layout or size of the dynamic generic-type, and only holds it by a pointer.
    652635The \CFA translator automatically generates \newterm{layout functions} for cases where the size, alignment, and offset array of a generic struct cannot be passed into a function from that function's caller.
    653636These layout functions take as arguments pointers to size and alignment variables and a caller-allocated array of member offsets, as well as the size and alignment of all @sized@ parameters to the generic structure (un@sized@ parameters are forbidden from being used in a context that affects layout).
     
    659642Whether a type is concrete, dtype-static, or dynamic is decided solely on the @forall@'s type parameters.
    660643This design allows opaque forward declarations of generic types, \eg @forall(otype T)@ @struct Box@ -- like in C, all uses of @Box(T)@ can be separately compiled, and callers from other translation units know the proper calling conventions to use.
    661 If the definition of a structure type is included in deciding whether a generic type is dynamic or concrete, some further types may be recognized as dtype-static (\eg @forall(otype T)@ @struct unique_ptr { T * p }@ does not depend on @T@ for its layout, but the existence of an @otype@ parameter means that it \emph{could}.);
    662 however, preserving separate compilation (and the associated C compatibility) in the existing design is judged to be an appropriate trade-off.
     644If the definition of a structure type is included in deciding whether a generic type is dynamic or concrete, some further types may be recognized as dtype-static (\eg @forall(otype T)@ @struct unique_ptr { T * p }@ does not depend on @T@ for its layout, but the existence of an @otype@ parameter means that it \emph{could}.), but preserving separate compilation (and the associated C compatibility) in the existing design is judged to be an appropriate trade-off.
    663645
    664646
     
    673655}
    674656\end{cfa}
    675 Since @pair( T *, T * )@ is a concrete type, there are no implicit parameters passed to @lexcmp@;
    676 hence, the generated code is identical to a function written in standard C using @void *@, yet the \CFA version is type checked to ensure members of both pairs and arguments to the comparison function match in type.
    677 
    678 Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \newterm{tag structures}.
    679 Sometimes, information is only used for type checking and can be omitted at runtime. \textcolor{blue}{REMOVE ``As an example, we have the following''}
     657Since @pair( T *, T * )@ is a concrete type, there are no implicit parameters passed to @lexcmp@, so the generated code is identical to a function written in standard C using @void *@, yet the \CFA version is type-checked to ensure the members of both pairs and the arguments to the comparison function match in type.
     658
     659Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \newterm{tag-structures}.
     660Sometimes information is only used for type-checking and can be omitted at runtime, \eg:
    680661\begin{cquote}
    681662\lstDeleteShortInline@%
     
    696677                                                        half_marathon;
    697678scalar(litres) two_pools = pool + pool;
    698 `marathon + pool;` // ERROR, mismatched types
     679`marathon + pool;`      // ERROR, mismatched types
    699680\end{cfa}
    700681\end{tabular}
    701682\lstMakeShortInline@%
    702683\end{cquote}
    703 Here, @scalar@ is a dtype-static type;
    704 hence, all uses have a single structure definition, containing @unsigned long@, and can share the same implementations of common functions like @?+?@.
     684@scalar@ is a dtype-static type, so all uses have a single structure definition, containing @unsigned long@, and can share the same implementations of common functions like @?+?@.
    705685These implementations may even be separately compiled, unlike \CC template functions.
    706 However, the \CFA type checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume.
     686However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume.
    707687
    708688
     
    710690\label{sec:tuples}
    711691
    712 In many languages, functions can return, at most, one value;
     692In many languages, functions can return at most one value;
    713693however, many operations have multiple outcomes, some exceptional.
    714694Consider C's @div@ and @remquo@ functions, which return the quotient and remainder for a division of integer and float values, respectively.
     
    721701double r = remquo( 13.5, 5.2, &q );                     $\C{// return remainder, alias quotient}$
    722702\end{cfa}
    723 Here, @div@ aggregates the quotient/remainder in a structure, whereas @remquo@ aliases a parameter to an argument.
     703@div@ aggregates the quotient/remainder in a structure, while @remquo@ aliases a parameter to an argument.
    724704Both approaches are awkward.
    725 % FIX
    726 Alternatively, a programming language can directly support returning multiple values, \eg \CFA provides the following. \textcolor{blue}{REPLACE ``in \CFA, we have the following'' WITH ``\CFA provides the following''}
     705Alternatively, a programming language can directly support returning multiple values, \eg in \CFA:
    727706\begin{cfa}
    728707[ int, int ] div( int num, int den );           $\C{// return two integers}$
     
    735714This approach is straightforward to understand and use;
    736715therefore, why do few programming languages support this obvious feature or provide it awkwardly?
    737 To answer, there are complex consequences that cascade through multiple aspects of the language, especially the type system.
    738 This section shows these consequences and how \CFA handles them.
     716To answer, there are complex consequences that cascade through multiple aspects of the language, especially the type-system.
     717This section show these consequences and how \CFA handles them.
    739718
    740719
    741720\subsection{Tuple Expressions}
    742721
    743 The addition of multiple-return-value functions (MRVFs) is \emph{useless} without a syntax for accepting multiple values at the call site.
     722The addition of multiple-return-value functions (MRVF) are \emph{useless} without a syntax for accepting multiple values at the call-site.
    744723The simplest mechanism for capturing the return values is variable assignment, allowing the values to be retrieved directly.
    745724As 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}.
    746725
    747 However, functions also use \newterm{composition} (nested calls), with the direct consequence that MRVFs must also support composition to be orthogonal with single-returning-value functions (SRVFs), \eg, \CFA provides the following. \textcolor{blue}{REPLACE ``As an example, we have the following'' WITH ``\CFA provides the following''}
     726However, functions also use \newterm{composition} (nested calls), with the direct consequence that MRVFs must also support composition to be orthogonal with single-returning-value functions (SRVF), \eg:
    748727\begin{cfa}
    749728printf( "%d %d\n", div( 13, 5 ) );                      $\C{// return values seperated into arguments}$
    750729\end{cfa}
    751730Here, the values returned by @div@ are composed with the call to @printf@ by flattening the tuple into separate arguments.
    752 However, the \CFA type-system must support significantly more complex composition.
     731However, the \CFA type-system must support significantly more complex composition:
    753732\begin{cfa}
    754733[ int, int ] foo$\(_1\)$( int );                        $\C{// overloaded foo functions}$
     
    757736`bar`( foo( 3 ), foo( 3 ) );
    758737\end{cfa}
    759 The type resolver only has the tuple return types to resolve the call to @bar@ as the @foo@ parameters are identical, which involves unifying the possible @foo@ functions with @bar@'s parameter list.
    760 No combination of @foo@s is an exact match with @bar@'s parameters;
    761 thus, the resolver applies C conversions.
    762 % FIX
     738The type-resolver only has the tuple return-types to resolve the call to @bar@ as the @foo@ parameters are identical, which involves unifying the possible @foo@ functions with @bar@'s parameter list.
     739No combination of @foo@s are an exact match with @bar@'s parameters, so the resolver applies C conversions.
    763740The minimal cost is @bar( foo@$_1$@( 3 ), foo@$_2$@( 3 ) )@, giving (@int@, {\color{ForestGreen}@int@}, @double@) to (@int@, {\color{ForestGreen}@double@}, @double@) with one {\color{ForestGreen}safe} (widening) conversion from @int@ to @double@ versus ({\color{red}@double@}, {\color{ForestGreen}@int@}, {\color{ForestGreen}@int@}) to ({\color{red}@int@}, {\color{ForestGreen}@double@}, {\color{ForestGreen}@double@}) with one {\color{red}unsafe} (narrowing) conversion from @double@ to @int@ and two safe conversions.
    764741
    765742
    766 \subsection{Tuple variables}
     743\subsection{Tuple Variables}
    767744
    768745An important observation from function composition is that new variable names are not required to initialize parameters from an MRVF.
    769 \CFA also allows declaration of tuple variables that can be initialized from an MRVF, since it can be awkward to declare multiple variables of different types.
    770 \newpage
     746\CFA also allows declaration of tuple variables that can be initialized from an MRVF, since it can be awkward to declare multiple variables of different types, \eg:
    771747\begin{cfa}
    772748[ int, int ] qr = div( 13, 5 );                         $\C{// tuple-variable declaration and initialization}$
    773749[ double, double ] qr = div( 13.5, 5.2 );
    774750\end{cfa}
    775 Here, the tuple variable name serves the same purpose as the parameter name(s).
     751where the tuple variable-name serves the same purpose as the parameter name(s).
    776752Tuple variables can be composed of any types, except for array types, since array sizes are generally unknown in C.
    777753
    778 One way to access the tuple variable components is with assignment or composition.
     754One way to access the tuple-variable components is with assignment or composition:
    779755\begin{cfa}
    780756[ q, r ] = qr;                                                          $\C{// access tuple-variable components}$
    781757printf( "%d %d\n", qr );
    782758\end{cfa}
    783 \CFA also supports \newterm{tuple indexing} to access single components of a tuple expression. \textcolor{blue}{REMOVE ``as follows''}
     759\CFA also supports \newterm{tuple indexing} to access single components of a tuple expression:
    784760\begin{cfa}
    785761[int, int] * p = &qr;                                           $\C{// tuple pointer}$
     
    792768
    793769
    794 \subsection{Flattening and restructuring}
     770\subsection{Flattening and Restructuring}
    795771
    796772In function call contexts, tuples support implicit flattening and restructuring conversions.
    797773Tuple flattening recursively expands a tuple into the list of its basic components.
    798 Tuple structuring packages a list of expressions into a value of tuple type.
     774Tuple structuring packages a list of expressions into a value of tuple type, \eg:
    799775\begin{cfa}
    800776int f( int, int );
     
    807783h( x, y );                                                                      $\C{// flatten and structure}$
    808784\end{cfa}
    809 In the call to @f@, @x@ is implicitly flattened so the components of @x@ are passed as two arguments.
     785In the call to @f@, @x@ is implicitly flattened so the components of @x@ are passed as the two arguments.
    810786In the call to @g@, the values @y@ and @10@ are structured into a single argument of type @[int, int]@ to match the parameter type of @g@.
    811 Finally, in the call to @h@, @x@ is flattened to yield an argument list of length 3, of which the first component of @x@ is passed as the first parameter of @h@, and the second component \textcolor{blue}{CHANGE ``components'' TO ``component''} of @x@ and @y@ are structured into the second argument of type @[int, int]@.
    812 The flexible structure of tuples permits a simple and expressive function call syntax to work seamlessly with both SRVFs and MRVFs \textcolor{blue}{REMOVE ``and''} with any number of arguments of arbitrarily complex structure.
    813 
    814 
    815 \subsection{Tuple assignment}
     787Finally, in the call to @h@, @x@ is flattened to yield an argument list of length 3, of which the first component of @x@ is passed as the first parameter of @h@, and the second component of @x@ and @y@ are structured into the second argument of type @[int, int]@.
     788The flexible structure of tuples permits a simple and expressive function call syntax to work seamlessly with both SRVF and MRVF, and with any number of arguments of arbitrarily complex structure.
     789
     790
     791\subsection{Tuple Assignment}
    816792
    817793An assignment where the left side is a tuple type is called \newterm{tuple assignment}.
    818 There are two kinds of tuple assignment depending on whether the right side of the assignment operator has a tuple type or a nontuple type, called \newterm{multiple} and \newterm{mass assignment}, respectively.
     794There are two kinds of tuple assignment depending on whether the right side of the assignment operator has a tuple type or a non-tuple type, called \newterm{multiple} and \newterm{mass assignment}, respectively.
    819795\begin{cfa}
    820796int x = 10;
     
    826802[y, x] = 3.14;                                                          $\C{// mass assignment}$
    827803\end{cfa}
    828 Both kinds of tuple assignment have parallel semantics, so that each value on the left and right sides is evaluated before any assignments occur.
     804Both kinds of tuple assignment have parallel semantics, so that each value on the left and right side is evaluated before any assignments occur.
    829805As a result, it is possible to swap the values in two variables without explicitly creating any temporary variables or calling a function, \eg, @[x, y] = [y, x]@.
    830 This semantics means mass assignment differs from C cascading
    831 \newpage
    832 assignment (\eg @a = b = c@) in that conversions are applied in each individual assignment, which prevents data loss from the chain of conversions that can happen during a cascading assignment.
    833 For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, yielding @y == 3.14@ and @x == 3@, whereas C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, yielding @3@ in @y@ and @x@.
     806This semantics means mass assignment differs from C cascading assignment (\eg @a = b = c@) in that conversions are applied in each individual assignment, which prevents data loss from the chain of conversions that can happen during a cascading assignment.
     807For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, yielding @y == 3.14@ and @x == 3@;
     808whereas, C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, yielding @3@ in @y@ and @x@.
    834809Finally, tuple assignment is an expression where the result type is the type of the left-hand side of the assignment, just like all other assignment expressions in C.
    835 This example shows mass, multiple, and cascading assignment used in one expression.
     810This example shows mass, multiple, and cascading assignment used in one expression:
    836811\begin{cfa}
    837812[void] f( [int, int] );
     
    840815
    841816
    842 \subsection{Member access}
    843 
    844 It is also possible to access multiple members from a single expression using a \newterm{member access}.
    845 The result is a single tuple-valued expression whose type is the tuple of the types of the members.
     817\subsection{Member Access}
     818
     819It is also possible to access multiple members from a single expression using a \newterm{member-access}.
     820The result is a single tuple-valued expression whose type is the tuple of the types of the members, \eg:
    846821\begin{cfa}
    847822struct S { int x; double y; char * z; } s;
     
    857832[int, int, int] y = x.[2, 0, 2];                        $\C{// duplicate: [y.0, y.1, y.2] = [x.2, x.0.x.2]}$
    858833\end{cfa}
    859 It is also possible for a member access to contain other member accesses. \textcolor{blue}{REMOVE ``, as follows.''}
     834It is also possible for a member access to contain other member accesses, \eg:
    860835\begin{cfa}
    861836struct A { double i; int j; };
     
    924899
    925900Tuples also integrate with \CFA polymorphism as a kind of generic type.
    926 Due to the implicit flattening and structuring conversions involved in argument passing, @otype@ and @dtype@ parameters are restricted to matching only with nontuple types.
     901Due to the implicit flattening and structuring conversions involved in argument passing, @otype@ and @dtype@ parameters are restricted to matching only with non-tuple types, \eg:
    927902\begin{cfa}
    928903forall( otype T, dtype U ) void f( T x, U * y );
    929904f( [5, "hello"] );
    930905\end{cfa}
    931 Here, @[5, "hello"]@ is flattened, giving argument list @5, "hello"@, and @T@ binds to @int@ and @U@ binds to @const char@.
     906where @[5, "hello"]@ is flattened, giving argument list @5, "hello"@, and @T@ binds to @int@ and @U@ binds to @const char@.
    932907Tuples, however, may contain polymorphic components.
    933908For example, a plus operator can be written to sum two triples.
     
    947922g( 5, 10.21 );
    948923\end{cfa}
    949 \newpage
    950924Hence, function parameter and return lists are flattened for the purposes of type unification allowing the example to pass expression resolution.
    951925This relaxation is possible by extending the thunk scheme described by Bilson~\cite{Bilson03}.
     
    958932
    959933
    960 \subsection{Variadic tuples}
     934\subsection{Variadic Tuples}
    961935\label{sec:variadic-tuples}
    962936
    963 To define variadic functions, \CFA adds a new kind of type parameter, \ie @ttype@ (tuple type).
    964 Matching against a @ttype@ parameter consumes all the remaining argument components and packages them into a tuple, binding to the resulting tuple of types.
    965 In a given parameter list, there must be, at most, one @ttype@ parameter that occurs last, which matches normal variadic semantics, with a strong feeling of similarity to \CCeleven variadic templates.
     937To define variadic functions, \CFA adds a new kind of type parameter, @ttype@ (tuple type).
     938Matching against a @ttype@ parameter consumes all remaining argument components and packages them into a tuple, binding to the resulting tuple of types.
     939In a given parameter list, there must be at most one @ttype@ parameter that occurs last, which matches normal variadic semantics, with a strong feeling of similarity to \CCeleven variadic templates.
    966940As such, @ttype@ variables are also called \newterm{argument packs}.
    967941
     
    969943Since nothing is known about a parameter pack by default, assertion parameters are key to doing anything meaningful.
    970944Unlike variadic templates, @ttype@ polymorphic functions can be separately compiled.
    971 For example, the following is a \textcolor{blue}{CHANGE ``As an example, we have the following'' TO ``For example, the following is a''} generalized @sum@ function.
     945For example, a generalized @sum@ function:
    972946\begin{cfa}
    973947int sum$\(_0\)$() { return 0; }
     
    978952\end{cfa}
    979953Since @sum@\(_0\) does not accept any arguments, it is not a valid candidate function for the call @sum(10, 20, 30)@.
    980 In order to call @sum@\(_1\), @10@ is matched with @x@, and the argument resolution moves on to the argument pack @rest@, which consumes the remainder of the argument list, and @Params@ is bound to @[20, 30]@.
     954In order to call @sum@\(_1\), @10@ is matched with @x@, and the argument resolution moves on to the argument pack @rest@, which consumes the remainder of the argument list and @Params@ is bound to @[20, 30]@.
    981955The process continues until @Params@ is bound to @[]@, requiring an assertion @int sum()@, which matches @sum@\(_0\) and terminates the recursion.
    982956Effectively, this algorithm traces as @sum(10, 20, 30)@ $\rightarrow$ @10 + sum(20, 30)@ $\rightarrow$ @10 + (20 + sum(30))@ $\rightarrow$ @10 + (20 + (30 + sum()))@ $\rightarrow$ @10 + (20 + (30 + 0))@.
    983957
    984 It is reasonable to take the @sum@ function a step further to enforce a minimum number of arguments.
     958It is reasonable to take the @sum@ function a step further to enforce a minimum number of arguments:
    985959\begin{cfa}
    986960int sum( int x, int y ) { return x + y; }
     
    989963}
    990964\end{cfa}
    991 One more step permits the summation of any sumable type with all arguments of the same type.
     965One more step permits the summation of any sumable type with all arguments of the same type:
    992966\begin{cfa}
    993967trait sumable( otype T ) {
     
    1003977Unlike C variadic functions, it is unnecessary to hard code the number and expected types.
    1004978Furthermore, this code is extendable for any user-defined type with a @?+?@ operator.
    1005 Summing \textcolor{blue}{REMOVE ``up''} arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators.
     979Summing arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators.
    1006980
    1007981It is also possible to write a type-safe variadic print function to replace @printf@:
     
    1018992This example showcases a variadic-template-like decomposition of the provided argument list.
    1019993The individual @print@ functions allow printing a single element of a type.
    1020 The polymorphic @print@ allows printing any list of types, where each individual type has a @print@ function.
     994The polymorphic @print@ allows printing any list of types, where as each individual type has a @print@ function.
    1021995The individual print functions can be used to build up more complicated @print@ functions, such as @S@, which cannot be done with @printf@ in C.
    1022996This mechanism is used to seamlessly print tuples in the \CFA I/O library (see Section~\ref{s:IOLibrary}).
    1023997
    1024998Finally, it is possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions.
    1025 For example, it is possible to write @new@ as a library function.
     999For example, it is possible to write @new@ as a library function:
    10261000\begin{cfa}
    10271001forall( otype R, otype S ) void ?{}( pair(R, S) *, R, S );
     
    10321006\end{cfa}
    10331007The @new@ function provides the combination of type-safe @malloc@ with a \CFA constructor call, making it impossible to forget constructing dynamically allocated objects.
    1034 This function provides the type safety of @new@ in \CC, without the need to specify the allocated type again, due to return-type inference.
     1008This function provides the type-safety of @new@ in \CC, without the need to specify the allocated type again, thanks to return-type inference.
    10351009
    10361010
     
    10381012
    10391013Tuples are implemented in the \CFA translator via a transformation into \newterm{generic types}.
    1040 For each $N$, the first time an $N$-tuple is seen in a scope, a generic type with $N$ type parameters is generated.
    1041 For example, the following \textcolor{blue}{CHANGE ``, as follows:'' TO ``For example, the following''}
     1014For each $N$, the first time an $N$-tuple is seen in a scope a generic type with $N$ type parameters is generated, \eg:
    10421015\begin{cfa}
    10431016[int, int] f() {
     
    10461019}
    10471020\end{cfa}
    1048 is transformed into
     1021is transformed into:
    10491022\begin{cfa}
    10501023forall( dtype T0, dtype T1 | sized(T0) | sized(T1) ) struct _tuple2 {
     
    11121085
    11131086The various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions.
    1114 A variable is generated to store the value produced by a statement expression, since its members may need to be constructed with a nontrivial constructor and it may need to be referred to multiple time, \eg in a unique expression.
     1087A variable is generated to store the value produced by a statement expression, since its members may need to be constructed with a non-trivial constructor and it may need to be referred to multiple time, \eg in a unique expression.
    11151088The use of statement expressions allows the translator to arbitrarily generate additional temporary variables as needed, but binds the implementation to a non-standard extension of the C language.
    11161089However, there are other places where the \CFA translator makes use of GNU C extensions, such as its use of nested functions, so this restriction is not new.
     
    11201093\section{Control Structures}
    11211094
    1122 \CFA identifies inconsistent, problematic, and missing control structures in C, as well as extends, modifies, and adds control structures to increase functionality and safety.
    1123 
    1124 
    1125 \subsection{\texorpdfstring{\protect\lstinline@if@ statement}{if statement}}
    1126 
    1127 The @if@ expression allows declarations, similar to the @for@ declaration expression.
     1095\CFA identifies inconsistent, problematic, and missing control structures in C, and extends, modifies, and adds control structures to increase functionality and safety.
     1096
     1097
     1098\subsection{\texorpdfstring{\protect\lstinline@if@ Statement}{if Statement}}
     1099
     1100The @if@ expression allows declarations, similar to @for@ declaration expression:
    11281101\begin{cfa}
    11291102if ( int x = f() ) ...                                          $\C{// x != 0}$
     
    11321105\end{cfa}
    11331106Unless 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.}
    1134 The scope of the declaration(s) is local to the @if@ statement but exists within both the ``then'' and ``else'' clauses.
    1135 
    1136 
    1137 \subsection{\texorpdfstring{\protect\lstinline@switch@ statement}{switch statement}}
     1107The scope of the declaration(s) is local to the @if@ statement but exist within both the ``then'' and ``else'' clauses.
     1108
     1109
     1110\subsection{\texorpdfstring{\protect\lstinline@switch@ Statement}{switch Statement}}
    11381111
    11391112There 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.
    11401113
    1141 C has no shorthand for specifying a list of case values, whether the list is noncontiguous or contiguous\footnote{C provides this mechanism via fall through.}.
    1142 \CFA provides a shorthand for a noncontiguous list:
     1114C 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.}.
     1115\CFA provides a shorthand for a non-contiguous list:
    11431116\begin{cquote}
    11441117\lstDeleteShortInline@%
     
    11551128\lstMakeShortInline@%
    11561129\end{cquote}
    1157 for a contiguous list:\footnote{gcc has the same mechanism but awkward syntax, \lstinline@2 ...42@, as a space is required after a number;
    1158 otherwise, the first period is a decimal point.}
     1130for a contiguous list:\footnote{gcc has the same mechanism but awkward syntax, \lstinline@2 ...42@, as a space is required after a number, otherwise the first period is a decimal point.}
    11591131\begin{cquote}
    11601132\lstDeleteShortInline@%
     
    11871159}
    11881160\end{cfa}
    1189 \CFA precludes this form of transfer \emph{into} a control structure because it causes an undefined behavior, especially with respect to missed initialization, and provides very limited functionality.
    1190 
    1191 C allows placement of declaration within the @switch@ body and unreachable code at the start, resulting in an undefined behavior.
     1161\CFA precludes this form of transfer \emph{into} a control structure because it causes undefined behaviour, especially with respect to missed initialization, and provides very limited functionality.
     1162
     1163C allows placement of declaration within the @switch@ body and unreachable code at the start, resulting in undefined behaviour:
    11921164\begin{cfa}
    11931165switch ( x ) {
     
    12061178
    12071179C @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};
    1208 @case@ clauses are made disjoint by the @break@
    1209 \newpage
    1210 \noindent
    1211 statement.
     1180@case@ clauses are made disjoint by the @break@ statement.
    12121181While fall through \emph{is} a useful form of control flow, it does not match well with programmer intuition, resulting in errors from missing @break@ statements.
    1213 For backward compatibility, \CFA provides a \emph{new} control structure, \ie @choose@, which mimics @switch@, but reverses the meaning of fall through (see Figure~\ref{f:ChooseSwitchStatements}), similar to Go.
     1182For 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}), similar to Go.
    12141183
    12151184\begin{figure}
    12161185\centering
    1217 \fontsize{9bp}{11bp}\selectfont
    12181186\lstDeleteShortInline@%
    12191187\begin{tabular}{@{}l|@{\hspace{\parindentlnth}}l@{}}
     
    12521220\end{tabular}
    12531221\lstMakeShortInline@%
    1254 \caption{\lstinline|choose| versus \lstinline|switch| statements}
     1222\caption{\lstinline|choose| versus \lstinline|switch| Statements}
    12551223\label{f:ChooseSwitchStatements}
    1256 \vspace*{-11pt}
    12571224\end{figure}
    12581225
    1259 Finally, Figure~\ref{f:FallthroughStatement} shows @fallthrough@ may appear in contexts other than terminating a @case@ clause and have an explicit transfer label allowing separate cases but common final code for a set of cases.
     1226Finally, Figure~\ref{f:FallthroughStatement} shows @fallthrough@ may appear in contexts other than terminating a @case@ clause, and have an explicit transfer label allowing separate cases but common final-code for a set of cases.
    12601227The target label must be below the @fallthrough@ and may not be nested in a control structure, \ie @fallthrough@ cannot form a loop, and the target label must be at the same or higher level as the containing @case@ clause and located at the same level as a @case@ clause;
    12611228the target label may be case @default@, but only associated with the current @switch@/@choose@ statement.
     
    12631230\begin{figure}
    12641231\centering
    1265 \fontsize{9bp}{11bp}\selectfont
    12661232\lstDeleteShortInline@%
    12671233\begin{tabular}{@{}l|@{\hspace{\parindentlnth}}l@{}}
     
    12921258\end{tabular}
    12931259\lstMakeShortInline@%
    1294 \caption{\lstinline|fallthrough| statement}
     1260\caption{\lstinline|fallthrough| Statement}
    12951261\label{f:FallthroughStatement}
    1296 \vspace*{-11pt}
    12971262\end{figure}
    12981263
    12991264
    1300 \vspace*{-8pt}
    1301 \subsection{\texorpdfstring{Labeled \protect\lstinline@continue@ / \protect\lstinline@break@}{Labeled continue / break}}
     1265\subsection{\texorpdfstring{Labelled \protect\lstinline@continue@ / \protect\lstinline@break@}{Labelled continue / break}}
    13021266
    13031267While C provides @continue@ and @break@ statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
    1304 Unfortunately, this restriction forces programmers to use @goto@ to achieve the equivalent control flow for more than one level of nesting.
    1305 To prevent having to switch to the @goto@, \CFA extends @continue@ and @break@ with a target label to support static multilevel exit~\cite{Buhr85}, as in Java.
     1268Unfortunately, this restriction forces programmers to use @goto@ to achieve the equivalent control-flow for more than one level of nesting.
     1269To prevent having to switch to the @goto@, \CFA extends the @continue@ and @break@ with a target label to support static multi-level exit~\cite{Buhr85}, as in Java.
    13061270For both @continue@ and @break@, the target label must be directly associated with a @for@, @while@ or @do@ statement;
    13071271for @break@, the target label can also be associated with a @switch@, @if@ or compound (@{}@) statement.
    1308 Figure~\ref{f:MultiLevelExit} shows @continue@ and @break@ indicating the specific control structure and the corresponding C program using only @goto@ and labels.
    1309 The innermost loop has seven exit points, which cause a continuation or termination of one or more of the seven nested control structures.
     1272Figure~\ref{f:MultiLevelExit} shows @continue@ and @break@ indicating the specific control structure, and the corresponding C program using only @goto@ and labels.
     1273The innermost loop has 7 exit points, which cause continuation or termination of one or more of the 7 nested control-structures.
    13101274
    13111275\begin{figure}
    1312 \fontsize{9bp}{11bp}\selectfont
    13131276\lstDeleteShortInline@%
    13141277\begin{tabular}{@{\hspace{\parindentlnth}}l|@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
     
    13751338\end{tabular}
    13761339\lstMakeShortInline@%
    1377 \caption{Multilevel exit}
     1340\caption{Multi-level Exit}
    13781341\label{f:MultiLevelExit}
    1379 \vspace*{-5pt}
    13801342\end{figure}
    13811343
    1382 With respect to safety, both labeled @continue@ and @break@ are @goto@ restricted in the following ways.
    1383 \begin{list}{$\bullet$}{\topsep=4pt\itemsep=0pt\parsep=0pt}
     1344With respect to safety, both labelled @continue@ and @break@ are a @goto@ restricted in the following ways:
     1345\begin{itemize}
    13841346\item
    13851347They cannot create a loop, which means only the looping constructs cause looping.
     
    13871349\item
    13881350They cannot branch into a control structure.
    1389 This restriction prevents missing declarations and/or initializations at the start of a control structure resulting in an undefined behavior.
    1390 \end{list}
    1391 The advantage of the labeled @continue@/@break@ is allowing static multilevel exits without having to use the @goto@ statement and tying control flow to the target control structure rather than an arbitrary point in a program.
    1392 Furthermore, the location of the label at the \emph{beginning} of the target control structure informs the reader (eye candy) that complex control flow is
    1393 occurring in the body of the control structure.
     1351This restriction prevents missing declarations and/or initializations at the start of a control structure resulting in undefined behaviour.
     1352\end{itemize}
     1353The advantage of the labelled @continue@/@break@ is allowing static multi-level exits without having to use the @goto@ statement, and tying control flow to the target control structure rather than an arbitrary point in a program.
     1354Furthermore, the location of the label at the \emph{beginning} of the target control structure informs the reader (eye candy) that complex control-flow is occurring in the body of the control structure.
    13941355With @goto@, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader.
    1395 Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting the existing constructs.
     1356Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs.
    13961357Otherwise, the implicit targets of the current @continue@ and @break@, \ie the closest enclosing loop or @switch@, change as certain constructs are added or removed.
    13971358
    13981359
    1399 \vspace*{-5pt}
    1400 \subsection{Exception handling}
    1401 
    1402 The following framework for \CFA exception handling is in place, excluding some runtime type information and virtual functions.
     1360\subsection{Exception Handling}
     1361
     1362The following framework for \CFA exception-handling is in place, excluding some runtime type-information and virtual functions.
    14031363\CFA provides two forms of exception handling: \newterm{fix-up} and \newterm{recovery} (see Figure~\ref{f:CFAExceptionHandling})~\cite{Buhr92b,Buhr00a}.
    1404 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.
     1364Both 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.
    14051365\CFA restricts exception types to those defined by aggregate type @exception@.
    14061366The 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@).
    1407 If @resume@ or @throw@ has no exception type, it is a reresume/rethrow, which means that the current exception continues propagation.
     1367If @resume@ or @throw@ have no exception type, it is a reresume/rethrow, meaning the currently exception continues propagation.
    14081368If there is no current exception, the reresume/rethrow results in a runtime error.
    14091369
    14101370\begin{figure}
    1411 \fontsize{9bp}{11bp}\selectfont
    1412 \lstDeleteShortInline@%
    14131371\begin{cquote}
     1372\lstDeleteShortInline@%
    14141373\begin{tabular}{@{}l|@{\hspace{\parindentlnth}}l@{}}
    14151374\multicolumn{1}{@{}c|@{\hspace{\parindentlnth}}}{\textbf{Resumption}}   & \multicolumn{1}{c@{}}{\textbf{Termination}}   \\
     
    14421401\end{cfa}
    14431402\end{tabular}
     1403\lstMakeShortInline@%
    14441404\end{cquote}
    1445 \lstMakeShortInline@%
    1446 \caption{\CFA exception handling}
     1405\caption{\CFA Exception Handling}
    14471406\label{f:CFAExceptionHandling}
    1448 \vspace*{-5pt}
    14491407\end{figure}
    14501408
    1451 The set of exception types in a list of catch clauses may include both a resumption and a termination handler.
     1409The set of exception types in a list of catch clause may include both a resumption and termination handler:
    14521410\begin{cfa}
    14531411try {
     
    14631421The termination handler is available because the resumption propagation did not unwind the stack.
    14641422
    1465 An additional feature is conditional matching in a catch clause.
     1423An additional feature is conditional matching in a catch clause:
    14661424\begin{cfa}
    14671425try {
     
    14721430   catch ( IOError err ) { ... }                        $\C{// handler error from other files}$
    14731431\end{cfa}
    1474 Here, the throw inserts the failing file handle into the I/O exception.
    1475 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.
    1476 
    1477 The resumption raise can specify an alternate stack on which to raise an exception, called a \newterm{nonlocal raise}.
     1432where the throw inserts the failing file-handle into the I/O exception.
     1433Conditional catch cannot be trivially mimicked by other mechanisms because once an exception is caught, handler clauses in that @try@ statement are no longer eligible..
     1434
     1435The resumption raise can specify an alternate stack on which to raise an exception, called a \newterm{nonlocal raise}:
    14781436\begin{cfa}
    14791437resume( $\emph{exception-type}$, $\emph{alternate-stack}$ )
     
    14831441Nonlocal 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 handler returns.
    14841442
    1485 To facilitate nonlocal raise, \CFA provides dynamic enabling and disabling of nonlocal exception propagation.
    1486 The constructs for controlling propagation of nonlocal exceptions are the @enable@ and @disable@ blocks.
     1443To facilitate nonlocal raise, \CFA provides dynamic enabling and disabling of nonlocal exception-propagation.
     1444The constructs for controlling propagation of nonlocal exceptions are the @enable@ and the @disable@ blocks:
    14871445\begin{cquote}
    14881446\lstDeleteShortInline@%
     
    14901448\begin{cfa}
    14911449enable $\emph{exception-type-list}$ {
    1492         // allow nonlocal raise
     1450        // allow non-local raise
    14931451}
    14941452\end{cfa}
     
    14961454\begin{cfa}
    14971455disable $\emph{exception-type-list}$ {
    1498         // disallow nonlocal raise
     1456        // disallow non-local raise
    14991457}
    15001458\end{cfa}
     
    15041462The arguments for @enable@/@disable@ specify the exception types allowed to be propagated or postponed, respectively.
    15051463Specifying no exception type is shorthand for specifying all exception types.
    1506 Both @enable@ and @disable@ blocks can be nested;
    1507 turning propagation on/off on entry and on exit, the specified exception types are restored to their prior state.
    1508 Coroutines and tasks start with nonlocal exceptions disabled, allowing handlers to be put in place, before nonlocal exceptions are explicitly enabled.
     1464Both @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.
     1465Coroutines and tasks start with non-local exceptions disabled, allowing handlers to be put in place, before non-local exceptions are explicitly enabled.
    15091466\begin{cfa}
    15101467void main( mytask & t ) {                                       $\C{// thread starts here}$
    1511         // nonlocal exceptions disabled
    1512         try {                                                                   $\C{// establish handles for nonlocal exceptions}$
    1513                 enable {                                                        $\C{// allow nonlocal exception delivery}$
     1468        // non-local exceptions disabled
     1469        try {                                                                   $\C{// establish handles for non-local exceptions}$
     1470                enable {                                                        $\C{// allow non-local exception delivery}$
    15141471                        // task body
    15151472                }
     
    15191476\end{cfa}
    15201477
    1521 \textcolor{blue}{PARAGRAPH INDENT} Finally, \CFA provides a Java-like  @finally@ clause after the catch clauses.
     1478Finally, \CFA provides a Java like  @finally@ clause after the catch clauses:
    15221479\begin{cfa}
    15231480try {
     
    15281485}
    15291486\end{cfa}
    1530 The finally clause is always executed, \ie, if the try block ends normally or if an exception is raised.
     1487The finally clause is always executed, i.e., if the try block ends normally or if an exception is raised.
    15311488If an exception is raised and caught, the handler is run before the finally clause.
    15321489Like a destructor (see Section~\ref{s:ConstructorsDestructors}), a finally clause can raise an exception but not if there is an exception being propagated.
    1533 Mimicking the @finally@ clause with mechanisms like Resource Aquisition Is Initialization (RAII) is nontrivial when there are multiple types and local accesses.
    1534 
    1535 
    1536 \subsection{\texorpdfstring{\protect\lstinline{with} statement}{with statement}}
     1490Mimicking the @finally@ clause with mechanisms like RAII is non-trivial when there are multiple types and local accesses.
     1491
     1492
     1493\subsection{\texorpdfstring{\protect\lstinline{with} Statement}{with Statement}}
    15371494\label{s:WithStatement}
    15381495
    1539 Heterogeneous data are often aggregated into a structure/union.
    1540 To reduce syntactic noise, \CFA provides a @with@ statement (see section~4.F in the Pascal User Manual and Report~\cite{Pascal}) to elide aggregate member qualification by opening a scope containing the member identifiers.
     1496Heterogeneous data is often aggregated into a structure/union.
     1497To reduce syntactic noise, \CFA provides a @with@ statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate member-qualification by opening a scope containing the member identifiers.
    15411498\begin{cquote}
    15421499\vspace*{-\baselineskip}%???
     
    15661523Object-oriented programming languages only provide implicit qualification for the receiver.
    15671524
    1568 In detail, the @with@ statement has the form
     1525In detail, the @with@ statement has the form:
    15691526\begin{cfa}
    15701527$\emph{with-statement}$:
     
    15721529\end{cfa}
    15731530and may appear as the body of a function or nested within a function body.
    1574 Each expression in the expression list provides a type and object.
     1531Each expression in the expression-list provides a type and object.
    15751532The type must be an aggregate type.
    15761533(Enumerations are already opened.)
    1577 The object is the implicit qualifier for the open structure members.
     1534The object is the implicit qualifier for the open structure-members.
    15781535
    15791536All expressions in the expression list are open in parallel within the compound statement, which is different from Pascal, which nests the openings from left to right.
    1580 The difference between parallel and nesting occurs for members with the same name and type.
     1537The difference between parallel and nesting occurs for members with the same name and type:
    15811538\begin{cfa}
    15821539struct S { int `i`; int j; double m; } s, w;    $\C{// member i has same type in structure types S and T}$
     
    15921549}
    15931550\end{cfa}
    1594 For parallel semantics, both @s.i@ and @t.i@ are visible and, therefore, @i@ is ambiguous without qualification;
    1595 for nested semantics, @t.i@ hides @s.i@ and, therefore, @i@ implies @t.i@.
     1551For parallel semantics, both @s.i@ and @t.i@ are visible, so @i@ is ambiguous without qualification;
     1552for nested semantics, @t.i@ hides @s.i@, so @i@ implies @t.i@.
    15961553\CFA's ability to overload variables means members with the same name but different types are automatically disambiguated, eliminating most qualification when opening multiple aggregates.
    15971554Qualification or a cast is used to disambiguate.
    15981555
    1599 There is an interesting problem between parameters and the function body @with@.
     1556There is an interesting problem between parameters and the function-body @with@, \eg:
    16001557\begin{cfa}
    16011558void ?{}( S & s, int i ) with ( s ) {           $\C{// constructor}$
     
    16031560}
    16041561\end{cfa}
    1605 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@.
    1606 To solve this problem, parameters are treated like an initialized aggregate
     1562Here, 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@.
     1563To solve this problem, parameters are treated like an initialized aggregate:
    16071564\begin{cfa}
    16081565struct Params {
     
    16111568} params;
    16121569\end{cfa}
    1613 \newpage
    1614 and implicitly opened \emph{after} a function body open, to give them higher priority
     1570and implicitly opened \emph{after} a function-body open, to give them higher priority:
    16151571\begin{cfa}
    16161572void ?{}( S & s, int `i` ) with ( s ) `{` `with( $\emph{\color{red}params}$ )` {
     
    16181574} `}`
    16191575\end{cfa}
    1620 Finally, a cast may be used to disambiguate among overload variables in a @with@ expression
     1576Finally, a cast may be used to disambiguate among overload variables in a @with@ expression:
    16211577\begin{cfa}
    16221578with ( w ) { ... }                                                      $\C{// ambiguous, same name and no context}$
    16231579with ( (S)w ) { ... }                                           $\C{// unambiguous, cast}$
    16241580\end{cfa}
    1625 and @with@ expressions may be complex expressions with type reference (see Section~\ref{s:References}) to aggregate
     1581and @with@ expressions may be complex expressions with type reference (see Section~\ref{s:References}) to aggregate:
    16261582\begin{cfa}
    16271583struct S { int i, j; } sv;
     
    16471603\CFA attempts to correct and add to C declarations, while ensuring \CFA subjectively ``feels like'' C.
    16481604An important part of this subjective feel is maintaining C's syntax and procedural paradigm, as opposed to functional and object-oriented approaches in other systems languages such as \CC and Rust.
    1649 Maintaining the C approach means that C coding patterns remain not only useable but idiomatic in \CFA, reducing the mental burden of retraining C programmers and switching between C and \CFA development.
     1605Maintaining the C approach means that C coding-patterns remain not only useable but idiomatic in \CFA, reducing the mental burden of retraining C programmers and switching between C and \CFA development.
    16501606Nevertheless, some features from other approaches are undeniably convenient;
    16511607\CFA attempts to adapt these features to the C paradigm.
    16521608
    16531609
    1654 \subsection{Alternative declaration syntax}
     1610\subsection{Alternative Declaration Syntax}
    16551611
    16561612C declaration syntax is notoriously confusing and error prone.
    1657 For example, many C programmers are confused by a declaration as simple as the following. \textcolor{blue}{CHANGE ``simple a declaration as in'' TO ``declaration as simple as''}
     1613For example, many C programmers are confused by a declaration as simple as:
    16581614\begin{cquote}
    16591615\lstDeleteShortInline@%
     
    16671623\lstMakeShortInline@%
    16681624\end{cquote}
    1669 Is this an array of five pointers to integers or a pointer to an array of five integers?
     1625Is this an array of 5 pointers to integers or a pointer to an array of 5 integers?
    16701626If there is any doubt, it implies productivity and safety issues even for basic programs.
    16711627Another 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.
    1672 For example, a function returning a pointer to an array of integers is defined and used in the following way.
     1628For example, a function returning a pointer to an array of integers is defined and used in the following way:
    16731629\begin{cfa}
    16741630int `(*`f`())[`5`]` {...};                                      $\C{// definition}$
     
    16781634While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice.
    16791635
    1680 \newpage
    1681 \CFA provides its own type, variable, and function declarations, using a different syntax~\cite[pp.~856--859]{Buhr94a}.
    1682 The new declarations place qualifiers to the left of the base type, whereas C declarations place qualifiers to the right.
     1636\CFA provides its own type, variable and function declarations, using a different syntax~\cite[pp.~856--859]{Buhr94a}.
     1637The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right.
    16831638The qualifiers have the same meaning but are ordered left to right to specify a variable's type.
    16841639\begin{cquote}
     
    17061661\lstMakeShortInline@%
    17071662\end{cquote}
    1708 The only exception is bit-field specification, which always appears to the right of the base type.
     1663The only exception is bit-field specification, which always appear to the right of the base type.
    17091664% 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.
    17101665However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list.
    1711 For instance, variables @x@ and @y@ of type pointer to integer are defined in \CFA as \textcolor{blue}{REMOVE ``follows.''}
     1666For instance, variables @x@ and @y@ of type pointer to integer are defined in \CFA as follows:
    17121667\begin{cquote}
    17131668\lstDeleteShortInline@%
     
    17721727\end{comment}
    17731728
    1774 All specifiers (@extern@, @static@, \etc) and qualifiers (@const@, @volatile@, \etc) are used in the normal way with the new declarations and also appear left to right.
     1729All specifiers (@extern@, @static@, \etc) and qualifiers (@const@, @volatile@, \etc) are used in the normal way with the new declarations and also appear left to right, \eg:
    17751730\begin{cquote}
    17761731\lstDeleteShortInline@%
    17771732\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{\hspace{2\parindentlnth}}l@{}}
    17781733\multicolumn{1}{@{}c@{\hspace{2\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2\parindentlnth}}}{\textbf{C}}     \\
    1779 \begin{cfa}[basicstyle=\linespread{0.9}\fontsize{9bp}{12bp}\selectfont\sf]
     1734\begin{cfa}
    17801735extern const * const int x;
    17811736static const * [5] const int y;
    17821737\end{cfa}
    17831738&
    1784 \begin{cfa}[basicstyle=\linespread{0.9}\fontsize{9bp}{12bp}\selectfont\sf]
     1739\begin{cfa}
    17851740int extern const * const x;
    17861741static const int (* const y)[5]
    17871742\end{cfa}
    17881743&
    1789 \begin{cfa}[basicstyle=\linespread{0.9}\fontsize{9bp}{12bp}\selectfont\sf]
     1744\begin{cfa}
    17901745// external const pointer to const int
    17911746// internal const pointer to array of 5 const int
     
    17951750\end{cquote}
    17961751Specifiers must appear at the start of a \CFA function declaration\footnote{\label{StorageClassSpecifier}
    1797 The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature (see section~6.11.5(1) in ISO/IEC 9899~\cite{C11}).}.
     1752The 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}}.
    17981753
    17991754The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-function @sizeof@:
     
    18161771
    18171772The syntax of the new function-prototype declaration follows directly from the new function-definition syntax;
    1818 also, parameter names are optional.
     1773as well, parameter names are optional, \eg:
    18191774\begin{cfa}
    18201775[ int x ] f ( /* void */ );             $\C[2.5in]{// returning int with no parameters}$
     
    18241779[ * int, int ] j ( int );               $\C{// returning pointer to int and int with int parameter}$
    18251780\end{cfa}
    1826 This syntax allows a prototype declaration to be created by cutting and pasting the source text from the function-definition header (or vice versa).
    1827 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.
     1781This syntax allows a prototype declaration to be created by cutting and pasting source text from the function-definition header (or vice versa).
     1782Like 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:
    18281783\begin{cquote}
    18291784\lstDeleteShortInline@%
     
    18401795\lstMakeShortInline@%
    18411796\end{cquote}
    1842 Here, \CFA allows the last function in the list to define its body.
    1843 
    1844 The syntax for pointers to \CFA functions specifies the pointer name on the right.
     1797where \CFA allows the last function in the list to define its body.
     1798
     1799The syntax for pointers to \CFA functions specifies the pointer name on the right, \eg:
    18451800\begin{cfa}
    18461801* [ int x ] () fp;                              $\C{// pointer to function returning int with no parameters}$
     
    18491804* [ * int, int ] ( int ) jp;    $\C{// pointer to function returning pointer to int and int with int parameter}\CRT$
    18501805\end{cfa}
    1851 \newpage
    1852 \noindent
    1853 Note that the name of the function pointer is specified last, as for other variable declarations.
    1854 
    1855 Finally, new \CFA declarations may appear together with C declarations in the same program block but cannot be mixed within a specific declaration.
    1856 Therefore, a programmer has the option of either continuing to use traditional C declarations or taking advantage of the new style.
    1857 Clearly, both styles need to be supported for some time due to existing C-style header files, particularly for UNIX-like systems.
     1806Note, the name of the function pointer is specified last, as for other variable declarations.
     1807
     1808Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration.
     1809Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
     1810Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX-like systems.
    18581811
    18591812
     
    18631816All variables in C have an \newterm{address}, a \newterm{value}, and a \newterm{type};
    18641817at the position in the program's memory denoted by the address, there exists a sequence of bits (the value), with the length and semantic meaning of this bit sequence defined by the type.
    1865 The C type system does not always track the relationship between a value and its address;
    1866 a value that does not have a corresponding address is called an \newterm{rvalue} (for ``right-hand value''), whereas a value that does have an address is called an \newterm{lvalue} (for ``left-hand value'').
    1867 For example, in @int x; x = 42;@ the variable expression @x@ on the left-hand side of the assignment is an lvalue, whereas the constant expression @42@ on the right-hand side of the assignment is an rvalue.
    1868 Despite the nomenclature of ``left-hand'' and ``right-hand'', an expression's classification as an lvalue or an rvalue is entirely dependent on whether it has an address or not; in imperative programming, the address of a value is used for both reading and writing (mutating) a value, and as such, lvalues can be converted into rvalues and read from, but rvalues cannot be mutated because they lack a location to store the updated value.
     1818The C type-system does not always track the relationship between a value and its address;
     1819a value that does not have a corresponding address is called a \newterm{rvalue} (for ``right-hand value''), while a value that does have an address is called a \newterm{lvalue} (for ``left-hand value'').
     1820For example, in @int x; x = 42;@ the variable expression @x@ on the left-hand-side of the assignment is a lvalue, while the constant expression @42@ on the right-hand-side of the assignment is a rvalue.
     1821Despite the nomenclature of ``left-hand'' and ``right-hand'', an expression's classification as lvalue or rvalue is entirely dependent on whether it has an address or not; in imperative programming, the address of a value is used for both reading and writing (mutating) a value, and as such, lvalues can be converted to rvalues and read from, but rvalues cannot be mutated because they lack a location to store the updated value.
    18691822
    18701823Within a lexical scope, lvalue expressions have an \newterm{address interpretation} for writing a value or a \newterm{value interpretation} to read a value.
    1871 For example, in @x = y@, @x@ has an address interpretation, whereas @y@ has a value interpretation.
     1824For example, in @x = y@, @x@ has an address interpretation, while @y@ has a value interpretation.
    18721825While this duality of interpretation is useful, C lacks a direct mechanism to pass lvalues between contexts, instead relying on \newterm{pointer types} to serve a similar purpose.
    18731826In C, for any type @T@ there is a pointer type @T *@, the value of which is the address of a value of type @T@.
    1874 A pointer rvalue can be explicitly \newterm{dereferenced} to the pointed-to lvalue with the dereference operator @*?@, whereas the rvalue representing the address of an lvalue can be obtained with the address-of operator @&?@.
     1827A pointer rvalue can be explicitly \newterm{dereferenced} to the pointed-to lvalue with the dereference operator @*?@, while the rvalue representing the address of a lvalue can be obtained with the address-of operator @&?@.
     1828
    18751829\begin{cfa}
    18761830int x = 1, y = 2, * p1, * p2, ** p3;
     
    18801834*p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15);
    18811835\end{cfa}
     1836
    18821837Unfortunately, the dereference and address-of operators introduce a great deal of syntactic noise when dealing with pointed-to values rather than pointers, as well as the potential for subtle bugs because of pointer arithmetic.
    18831838For both brevity and clarity, it is desirable for the compiler to figure out how to elide the dereference operators in a complex expression such as the assignment to @*p2@ above.
    1884 However, since C defines a number of forms of \newterm{pointer arithmetic}, two similar expressions involving pointers to arithmetic types (\eg @*p1 + x@ and @p1 + x@) may each have well-defined but distinct semantics, introducing the possibility that a programmer may write one when they mean the other and precluding any simple algorithm for elision of dereference operators.
     1839However, since C defines a number of forms of \newterm{pointer arithmetic}, two similar expressions involving pointers to arithmetic types (\eg @*p1 + x@ and @p1 + x@) may each have well-defined but distinct semantics, introducing the possibility that a programmer may write one when they mean the other, and precluding any simple algorithm for elision of dereference operators.
    18851840To solve these problems, \CFA introduces reference types @T &@;
    1886 a @T &@ has exactly the same value as a @T *@, but where the @T *@ takes the address interpretation by default, a @T &@ takes the value interpretation by default, as below.
     1841a @T &@ has exactly the same value as a @T *@, but where the @T *@ takes the address interpretation by default, a @T &@ takes the value interpretation by default, as below:
     1842
    18871843\begin{cfa}
    18881844int x = 1, y = 2, & r1, & r2, && r3;
     
    18921848r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15);       $\C{// implicit dereferencing}$
    18931849\end{cfa}
     1850
    18941851Except for auto-dereferencing by the compiler, this reference example is exactly the same as the previous pointer example.
    1895 Hence, a reference behaves like a variable name---an lvalue expression that is interpreted as a value---but also has the type system track the address of that value.
    1896 One way to conceptualize a reference is via a rewrite rule, where the compiler inserts a dereference operator before the reference variable for each reference qualifier in the reference variable declaration;
    1897 thus, the previous example implicitly acts like the following.
     1852Hence, a reference behaves like a variable name -- an lvalue expression which is interpreted as a value -- but also has the type system track the address of that value.
     1853One way to conceptualize a reference is via a rewrite rule, where the compiler inserts a dereference operator before the reference variable for each reference qualifier in the reference variable declaration, so the previous example implicitly acts like:
     1854
    18981855\begin{cfa}
    18991856`*`r2 = ((`*`r1 + `*`r2) * (`**`r3 - `*`r1)) / (`**`r3 - 15);
    19001857\end{cfa}
     1858
    19011859References in \CFA are similar to those in \CC, with important improvements, which can be seen in the example above.
    19021860Firstly, \CFA does not forbid references to references.
    1903 This provides a much more orthogonal design for library \mbox{implementors}, obviating the need for workarounds such as @std::reference_wrapper@.
     1861This provides a much more orthogonal design for library implementors, obviating the need for workarounds such as @std::reference_wrapper@.
    19041862Secondly, \CFA references are rebindable, whereas \CC references have a fixed address.
    1905 Rebinding allows \CFA references to be default initialized (\eg to a null pointer\footnote{
    1906 While effort has been made into non-null reference checking in \CC and Java, the exercise seems moot for any nonmanaged languages (C/\CC), given that it only handles one of many different error situations, \eg using a pointer after its storage is deleted.}) and point to different addresses throughout their lifetime, like pointers.
     1863Rebinding allows \CFA references to be default-initialized (\eg to a null pointer\footnote{
     1864While effort has been made into non-null reference checking in \CC and Java, the exercise seems moot for any non-managed languages (C/\CC), given that it only handles one of many different error situations, \eg using a pointer after its storage is deleted.}) and point to different addresses throughout their lifetime, like pointers.
    19071865Rebinding is accomplished by extending the existing syntax and semantics of the address-of operator in C.
    19081866
    1909 In C, the address of an lvalue is always an rvalue, as, in general, that address is not stored anywhere in memory and does not itself have an address.
    1910 In \CFA, the address of a @T &@ is an lvalue @T *@, as the address of the underlying @T@ is stored in the reference and can thus be mutated there.
     1867In C, the address of a lvalue is always a rvalue, as in general that address is not stored anywhere in memory, and does not itself have an address.
     1868In \CFA, the address of a @T &@ is a lvalue @T *@, as the address of the underlying @T@ is stored in the reference, and can thus be mutated there.
    19111869The result of this rule is that any reference can be rebound using the existing pointer assignment semantics by assigning a compatible pointer into the address of the reference, \eg @&r1 = &x;@ above.
    19121870This rebinding occurs to an arbitrary depth of reference nesting;
    19131871loosely speaking, nested address-of operators produce a nested lvalue pointer up to the depth of the reference.
    19141872These explicit address-of operators can be thought of as ``cancelling out'' the implicit dereference operators, \eg @(&`*`)r1 = &x@ or @(&(&`*`)`*`)r3 = &(&`*`)r1@ or even @(&`*`)r2 = (&`*`)`*`r3@ for @&r2 = &r3@.
    1915 The precise rules are
     1873More precisely:
    19161874\begin{itemize}
    19171875\item
    1918 If @R@ is an rvalue of type @T &@$_1\cdots$ @&@$_r$, where $r \ge 1$ references (@&@ symbols), than @&R@ has type @T `*`&@$_{\color{red}2}\cdots$ @&@$_{\color{red}r}$, \ie @T@ pointer with $r-1$ references (@&@ symbols).
     1876if @R@ is an rvalue of type @T &@$_1\cdots$ @&@$_r$, where $r \ge 1$ references (@&@ symbols), than @&R@ has type @T `*`&@$_{\color{red}2}\cdots$ @&@$_{\color{red}r}$, \ie @T@ pointer with $r-1$ references (@&@ symbols).
    19191877\item
    1920 If @L@ is an lvalue of type @T &@$_1\cdots$ @&@$_l$, where $l \ge 0$ references (@&@ symbols), than @&L@ has type @T `*`&@$_{\color{red}1}\cdots$ @&@$_{\color{red}l}$, \ie @T@ pointer with $l$ references (@&@ symbols).
     1878if @L@ is an lvalue of type @T &@$_1\cdots$ @&@$_l$, where $l \ge 0$ references (@&@ symbols), than @&L@ has type @T `*`&@$_{\color{red}1}\cdots$ @&@$_{\color{red}l}$, \ie @T@ pointer with $l$ references (@&@ symbols).
    19211879\end{itemize}
    1922 Since pointers and references share the same internal representation, code using either is equally performant;
    1923 in fact, the \CFA compiler converts references into pointers internally, and the choice between them is made solely on convenience, \eg many pointer or value accesses.
     1880Since pointers and references share the same internal representation, code using either is equally performant; in fact the \CFA compiler converts references to pointers internally, and the choice between them is made solely on convenience, \eg many pointer or value accesses.
    19241881
    19251882By analogy to pointers, \CFA references also allow cv-qualifiers such as @const@:
     
    19361893There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, and return/temporary binding.
    19371894In each of these contexts, the address-of operator on the target lvalue is elided.
    1938 The syntactic motivation is clearest when considering overloaded operator assignment, \eg @int ?+=?(int &, int)@; given @int x, y@, the expected call syntax is @x += y@, not @&x += y@.
    1939 
    1940 More generally, this initialization of references from lvalues rather than pointers is an instance of an ``lvalue-to-reference'' conversion rather than an elision of the address-of operator;
     1895The syntactic motivation is clearest when considering overloaded operator-assignment, \eg @int ?+=?(int &, int)@; given @int x, y@, the expected call syntax is @x += y@, not @&x += y@.
     1896
     1897More generally, this initialization of references from lvalues rather than pointers is an instance of a ``lvalue-to-reference'' conversion rather than an elision of the address-of operator;
    19411898this conversion is used in any context in \CFA where an implicit conversion is allowed.
    1942 Similarly, use of the value pointed to by a reference in an rvalue context can be thought of as a ``reference-to-rvalue'' conversion, and \CFA also includes a qualifier-adding ``reference-to-reference'' conversion, analogous to the @T *@ to @const T *@ conversion in standard C.
    1943 The final reference conversion included in \CFA is an ``rvalue-to-reference'' conversion, implemented by means of an implicit temporary.
     1899Similarly, use of a the value pointed to by a reference in an rvalue context can be thought of as a ``reference-to-rvalue'' conversion, and \CFA also includes a qualifier-adding ``reference-to-reference'' conversion, analogous to the @T *@ to @const T *@ conversion in standard C.
     1900The final reference conversion included in \CFA is ``rvalue-to-reference'' conversion, implemented by means of an implicit temporary.
    19441901When an rvalue is used to initialize a reference, it is instead used to initialize a hidden temporary value with the same lexical scope as the reference, and the reference is initialized to the address of this temporary.
    19451902\begin{cfa}
     
    19491906f( 3, x + y, (S){ 1.0, 7.0 }, (int [3]){ 1, 2, 3 } ); $\C{// pass rvalue to lvalue \(\Rightarrow\) implicit temporary}$
    19501907\end{cfa}
    1951 This allows complex values to be succinctly and efficiently passed to functions, without the syntactic overhead of the explicit definition of a temporary variable or the runtime cost of pass-by-value.
    1952 \CC allows a similar binding, but only for @const@ references; the more general semantics of \CFA are an attempt to avoid the \newterm{const poisoning} problem~\cite{Taylor10}, in which the addition of a @const@ qualifier to one reference requires a cascading chain of added qualifiers.
    1953 
    1954 
    1955 \subsection{Type nesting}
    1956 
    1957 Nested types provide a mechanism to organize associated types and refactor a subset of members into a named aggregate (\eg subaggregates @name@, @address@, @department@, within aggregate @employe@).
    1958 Java nested types are dynamic (apply to objects), \CC are static (apply to the \lstinline[language=C++]@class@), and C hoists (refactors) nested types into the enclosing scope, which means there is no need for type qualification.
    1959 Since \CFA in not object oriented, adopting dynamic scoping does not make sense;
    1960 instead, \CFA adopts \CC static nesting, using the member-selection operator ``@.@'' for type qualification, as does Java, rather than the \CC type-selection operator ``@::@'' (see Figure~\ref{f:TypeNestingQualification}).
    1961 
     1908This allows complex values to be succinctly and efficiently passed to functions, without the syntactic overhead of explicit definition of a temporary variable or the runtime cost of pass-by-value.
     1909\CC allows a similar binding, but only for @const@ references; the more general semantics of \CFA are an attempt to avoid the \newterm{const poisoning} problem~\cite{Taylor10}, in which addition of a @const@ qualifier to one reference requires a cascading chain of added qualifiers.
     1910
     1911
     1912\subsection{Type Nesting}
     1913
     1914Nested types provide a mechanism to organize associated types and refactor a subset of members into a named aggregate (\eg sub-aggregates @name@, @address@, @department@, within aggregate @employe@).
     1915Java nested types are dynamic (apply to objects), \CC are static (apply to the \lstinline[language=C++]@class@), and C hoists (refactors) nested types into the enclosing scope, meaning there is no need for type qualification.
     1916Since \CFA in not object-oriented, adopting dynamic scoping does not make sense;
     1917instead \CFA adopts \CC static nesting, using the member-selection operator ``@.@'' for type qualification, as does Java, rather than the \CC type-selection operator ``@::@'' (see Figure~\ref{f:TypeNestingQualification}).
    19621918\begin{figure}
    19631919\centering
    1964 \fontsize{9bp}{11bp}\selectfont\sf
    19651920\lstDeleteShortInline@%
    19661921\begin{tabular}{@{}l@{\hspace{3em}}l|l@{}}
     
    20241979\end{tabular}
    20251980\lstMakeShortInline@%
    2026 \caption{Type nesting / qualification}
     1981\caption{Type Nesting / Qualification}
    20271982\label{f:TypeNestingQualification}
    2028 \vspace*{-8pt}
    20291983\end{figure}
    2030 
    20311984In the C left example, types @C@, @U@ and @T@ are implicitly hoisted outside of type @S@ into the containing block scope.
    20321985In the \CFA right example, the types are not hoisted and accessible.
    20331986
    20341987
    2035 \vspace*{-8pt}
    2036 \subsection{Constructors and destructors}
     1988\subsection{Constructors and Destructors}
    20371989\label{s:ConstructorsDestructors}
    20381990
    2039 One of the strengths (and weaknesses) of C is memory-management control, allowing resource release to be precisely specified versus unknown release with garbage-collected memory management.
     1991One of the strengths (and weaknesses) of C is memory-management control, allowing resource release to be precisely specified versus unknown release with garbage-collected memory-management.
    20401992However, this manual approach is verbose, and it is useful to manage resources other than memory (\eg file handles) using the same mechanism as memory.
    2041 \CC addresses these issues using RAII, implemented by means of \newterm{constructor} and \newterm{destructor} functions;
     1993\CC addresses these issues using Resource Aquisition Is Initialization (RAII), implemented by means of \newterm{constructor} and \newterm{destructor} functions;
    20421994\CFA adopts constructors and destructors (and @finally@) to facilitate RAII.
    2043 While constructors and destructors are a common feature of object-oriented programming languages, they are an independent capability allowing \CFA to adopt them while retaining a procedural paradigm.
    2044 Specifically, \CFA constructors and destructors are denoted by name and first parameter type versus name and nesting in an aggregate type.
     1995While constructors and destructors are a common feature of object-oriented programming-languages, they are an independent capability allowing \CFA to adopt them while retaining a procedural paradigm.
     1996Specifically, \CFA constructors and destructors are denoted by name and first parameter-type versus name and nesting in an aggregate type.
    20451997Constructor calls seamlessly integrate with existing C initialization syntax, providing a simple and familiar syntax to C programmers and allowing constructor calls to be inserted into legacy C code with minimal code changes.
    20461998
     
    20512003The constructor and destructor have return type @void@, and the first parameter is a reference to the object type to be constructed or destructed.
    20522004While the first parameter is informally called the @this@ parameter, as in object-oriented languages, any variable name may be used.
    2053 Both constructors and destructors allow additional parameters after the @this@ parameter for specifying values for initialization/deinitialization\footnote{
    2054 Destruction parameters are useful for specifying storage-management actions, such as deinitialize but not deallocate.}.
    2055 \begin{cfa}[basicstyle=\linespread{0.9}\fontsize{9bp}{11bp}\selectfont\sf]
     2005Both constructors and destructors allow additional parameters after the @this@ parameter for specifying values for initialization/de-initialization\footnote{
     2006Destruction parameters are useful for specifying storage-management actions, such as de-initialize but not deallocate.}.
     2007\begin{cfa}
    20562008struct VLA { int size, * data; };                       $\C{// variable length array of integers}$
    20572009void ?{}( VLA & vla ) with ( vla ) { size = 10;  data = alloc( size ); }  $\C{// default constructor}$
     
    20622014\end{cfa}
    20632015@VLA@ is a \newterm{managed type}\footnote{
    2064 A managed type affects the runtime environment versus a self-contained type.}: a type requiring a nontrivial constructor or destructor, or with a member of a managed type.
     2016A managed type affects the runtime environment versus a self-contained type.}: a type requiring a non-trivial constructor or destructor, or with a member of a managed type.
    20652017A managed type is implicitly constructed at allocation and destructed at deallocation to ensure proper interaction with runtime resources, in this case, the @data@ array in the heap.
    2066 For details of the code-generation placement of implicit constructor and destructor calls among complex executable statements, see section~2.2 in the work of Schlintz~\cite{Schluntz17}.
    2067 
    2068 \CFA also provides syntax for \newterm{initialization} and \newterm{copy}. \textcolor{blue}{REMOVE ``, as follows''}
     2018For details of the code-generation placement of implicit constructor and destructor calls among complex executable statements see~\cite[\S~2.2]{Schluntz17}.
     2019
     2020\CFA also provides syntax for \newterm{initialization} and \newterm{copy}:
    20692021\begin{cfa}
    20702022void ?{}( VLA & vla, int size, char fill = '\0' ) {  $\C{// initialization}$
     
    20752027}
    20762028\end{cfa}
    2077 (Note that the example is purposely simplified using shallow-copy semantics.)
    2078 An initialization constructor call has the same syntax as a C initializer, except that the initialization values are passed as arguments to a matching constructor (number and type of parameters).
     2029(Note, the example is purposely simplified using shallow-copy semantics.)
     2030An 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).
    20792031\begin{cfa}
    20802032VLA va = `{` 20, 0 `}`,  * arr = alloc()`{` 5, 0 `}`;
    20812033\end{cfa}
    2082 Note the use of a \newterm{constructor expression} to initialize the storage from the dynamic storage allocation.
     2034Note, the use of a \newterm{constructor expression} to initialize the storage from the dynamic storage-allocation.
    20832035Like \CC, the copy constructor has two parameters, the second of which is a value parameter with the same type as the first parameter;
    20842036appropriate care is taken to not recursively call the copy constructor when initializing the second parameter.
     
    20862038\CFA constructors may be explicitly called, like Java, and destructors may be explicitly called, like \CC.
    20872039Explicit calls to constructors double as a \CC-style \emph{placement syntax}, useful for construction of members in user-defined constructors and reuse of existing storage allocations.
    2088 Like the other operators in \CFA, there is a concise syntax for constructor/destructor function calls.
     2040Like the other operators in \CFA, there is a concise syntax for constructor/destructor function calls:
    20892041\begin{cfa}
    20902042{
     
    21022054To provide a uniform type interface for @otype@ polymorphism, the \CFA compiler automatically generates a default constructor, copy constructor, assignment operator, and destructor for all types.
    21032055These default functions can be overridden by user-generated versions.
    2104 For compatibility with the standard behavior of C, the default constructor and destructor for all basic, pointer, and reference types do nothing, whereas the copy constructor and assignment operator are bitwise copies;
    2105 if default zero initialization is desired, the default constructors can be overridden.
     2056For compatibility with the standard behaviour of C, the default constructor and destructor for all basic, pointer, and reference types do nothing, while the copy constructor and assignment operator are bitwise copies;
     2057if default zero-initialization is desired, the default constructors can be overridden.
    21062058For user-generated types, the four functions are also automatically generated.
    21072059@enum@ types are handled the same as their underlying integral type, and unions are also bitwise copied and no-op initialized and destructed.
    21082060For compatibility with C, a copy constructor from the first union member type is also defined.
    2109 For @struct@ types, each of the four functions is implicitly defined to call their corresponding functions on each member of the struct.
    2110 To better simulate the behavior of C initializers, a set of \newterm{member constructors} is also generated for structures.
    2111 A constructor is generated for each nonempty prefix of a structure's member list to copy-construct the members passed as parameters and default-construct the remaining members.
     2061For @struct@ types, each of the four functions are implicitly defined to call their corresponding functions on each member of the struct.
     2062To better simulate the behaviour of C initializers, a set of \newterm{member constructors} is also generated for structures.
     2063A constructor is generated for each non-empty prefix of a structure's member-list to copy-construct the members passed as parameters and default-construct the remaining members.
    21122064To allow users to limit the set of constructors available for a type, when a user declares any constructor or destructor, the corresponding generated function and all member constructors for that type are hidden from expression resolution;
    2113 similarly, the generated default constructor is hidden upon the declaration of any constructor.
     2065similarly, the generated default constructor is hidden upon declaration of any constructor.
    21142066These semantics closely mirror the rule for implicit declaration of constructors in \CC\cite[p.~186]{ANSI98:C++}.
    21152067
    2116 In some circumstance, programmers may not wish to have implicit constructor and destructor generation and calls.
    2117 In these cases, \CFA provides the initialization syntax \lstinline|S x `@=` {}|, and the object becomes unmanaged;
    2118 hence, implicit \mbox{constructor} and destructor calls are not generated.
     2068In some circumstance programmers may not wish to have implicit constructor and destructor generation and calls.
     2069In these cases, \CFA provides the initialization syntax \lstinline|S x `@=` {}|, and the object becomes unmanaged, so implicit constructor and destructor calls are not generated.
    21192070Any C initializer can be the right-hand side of an \lstinline|@=| initializer, \eg \lstinline|VLA a @= { 0, 0x0 }|, with the usual C initialization semantics.
    21202071The same syntax can be used in a compound literal, \eg \lstinline|a = (VLA)`@`{ 0, 0x0 }|, to create a C-style literal.
    2121 The point of \lstinline|@=| is to provide a migration path from legacy C code to \CFA, by providing a mechanism to incrementally convert into implicit initialization.
     2072The point of \lstinline|@=| is to provide a migration path from legacy C code to \CFA, by providing a mechanism to incrementally convert to implicit initialization.
    21222073
    21232074
     
    21272078\section{Literals}
    21282079
    2129 C already includes limited polymorphism for literals---@0@ can be either an integer or a pointer literal, depending on context, whereas the syntactic forms of literals of the various integer and float types are very similar, differing from each other only in suffix.
    2130 In 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 backward-compatible semantics.
     2080C 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.
     2081In 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.
    21312082
    21322083A 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.
    2133 \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 \textcolor{blue}{Q2 CHANGE ``IDEs'' TO ``integrated development environments (IDEs)''}, which must be extended to deal with this alternate use of the single quote.
     2084\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.
    21342085
    21352086
     
    21742125
    21752126In C, @0@ has the special property that it is the only ``false'' value;
    2176 by the standard, any value that compares equal to @0@ is false, whereas any value that compares unequal to @0@ is true.
    2177 As such, an expression @x@ in any Boolean context (such as the condition of an @if@ or @while@ statement, or the arguments to @&&@, @||@, or @?:@\,) can be rewritten as @x != 0@ without changing its semantics.
     2127by the standard, any value that compares equal to @0@ is false, while any value that compares unequal to @0@ is true.
     2128As such, an expression @x@ in any boolean context (such as the condition of an @if@ or @while@ statement, or the arguments to @&&@, @||@, or @?:@\,) can be rewritten as @x != 0@ without changing its semantics.
    21782129Operator overloading in \CFA provides a natural means to implement this truth-value comparison for arbitrary types, but the C type system is not precise enough to distinguish an equality comparison with @0@ from an equality comparison with an arbitrary integer or pointer.
    21792130To provide this precision, \CFA introduces a new type @zero_t@ as the type of literal @0@ (somewhat analagous to @nullptr_t@ and @nullptr@ in \CCeleven);
     
    21812132With this addition, \CFA rewrites @if (x)@ and similar expressions to @if ( (x) != 0 )@ or the appropriate analogue, and any type @T@ is ``truthy'' by defining an operator overload @int ?!=?( T, zero_t )@.
    21822133\CC makes types truthy by adding a conversion to @bool@;
    2183 prior to the addition of explicit cast operators in \CCeleven, this approach had the pitfall of making truthy types transitively convertible into any numeric type;
     2134prior to the addition of explicit cast operators in \CCeleven, this approach had the pitfall of making truthy types transitively convertable to any numeric type;
    21842135\CFA avoids this issue.
    21852136
     
    21922143
    21932144
    2194 \subsection{User literals}
     2145\subsection{User Literals}
    21952146
    21962147For readability, it is useful to associate units to scale literals, \eg weight (stone, pound, kilogram) or time (seconds, minutes, hours).
    2197 The left of Figure~\ref{f:UserLiteral} shows the \CFA alternative call syntax (postfix: literal argument before function name), using the backquote, to convert basic literals into user literals.
     2148The left of Figure~\ref{f:UserLiteral} shows the \CFA alternative call-syntax (postfix: literal argument before function name), using the backquote, to convert basic literals into user literals.
    21982149The backquote is a small character, making the unit (function name) predominate.
    2199 For examples, the multiprecision integer type in Section~\ref{s:MultiPrecisionIntegers} has the following user literals.
     2150For examples, the multi-precision integer-type in Section~\ref{s:MultiPrecisionIntegers} has user literals:
    22002151{\lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
    22012152\begin{cfa}
     
    22032154y = "12345678901234567890123456789"|`mp| + "12345678901234567890123456789"|`mp|;
    22042155\end{cfa}
    2205 Because \CFA uses a standard function, all types and literals are applicable, as well as overloading and conversions, where @?`@ \textcolor{blue}{USE CHARACTER \lstinline@`@ NOT \textsf{'}} denotes a postfix-function name and @`@ \textcolor{blue}{USE CHARACTER \lstinline@`@ NOT `} denotes a postfix-function call.
     2156Because \CFA uses a standard function, all types and literals are applicable, as well as overloading and conversions, where @?`@ denotes a postfix-function name and @`@ denotes a postfix-function call.
    22062157}%
    22072158\begin{cquote}
     
    22452196\end{cquote}
    22462197
    2247 The right of Figure~\ref{f:UserLiteral} shows the equivalent \CC version using the underscore for the call syntax.
     2198The right of Figure~\ref{f:UserLiteral} shows the equivalent \CC version using the underscore for the call-syntax.
    22482199However, \CC restricts the types, \eg @unsigned long long int@ and @long double@ to represent integral and floating literals.
    22492200After which, user literals must match (no conversions);
     
    22522203\begin{figure}
    22532204\centering
    2254 \fontsize{9bp}{11bp}\selectfont
    22552205\lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
    22562206\lstDeleteShortInline@%
     
    23082258\end{tabular}
    23092259\lstMakeShortInline@%
    2310 \caption{User literal}
     2260\caption{User Literal}
    23112261\label{f:UserLiteral}
    23122262\end{figure}
     
    23162266\label{sec:libraries}
    23172267
    2318 As stated in Section~\ref{sec:poly-fns}, \CFA inherits a large corpus of library code, where other programming languages must rewrite or provide fragile interlanguage communication with C.
     2268As stated in Section~\ref{sec:poly-fns}, \CFA inherits a large corpus of library code, where other programming languages must rewrite or provide fragile inter-language communication with C.
    23192269\CFA has replacement libraries condensing hundreds of existing C names into tens of \CFA overloaded names, all without rewriting the actual computations.
    2320 In many cases, the interface is an inline wrapper providing overloading during compilation but of zero cost at runtime.
     2270In many cases, the interface is an inline wrapper providing overloading during compilation but zero cost at runtime.
    23212271The following sections give a glimpse of the interface reduction to many C libraries.
    23222272In 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.
     
    23262276
    23272277C library @limits.h@ provides lower and upper bound constants for the basic types.
    2328 \CFA name overloading is used to condense these typed constants.
     2278\CFA name overloading is used to condense these typed constants, \eg:
    23292279\begin{cquote}
    23302280\lstDeleteShortInline@%
     
    23452295\lstMakeShortInline@%
    23462296\end{cquote}
    2347 The result is a significant reduction in names to access typed constants. \textcolor{blue}{REMOVE ``, as follows.''}
     2297The result is a significant reduction in names to access typed constants, \eg:
    23482298\begin{cquote}
    23492299\lstDeleteShortInline@%
     
    23712321
    23722322C library @math.h@ provides many mathematical functions.
    2373 \CFA function overloading is used to condense these mathematical functions.
     2323\CFA function overloading is used to condense these mathematical functions, \eg:
    23742324\begin{cquote}
    23752325\lstDeleteShortInline@%
     
    23902340\lstMakeShortInline@%
    23912341\end{cquote}
    2392 The result is a significant reduction in names to access math functions. \textcolor{blue}{REMOVE ``, as follows.''}
     2342The result is a significant reduction in names to access math functions, \eg:
    23932343\begin{cquote}
    23942344\lstDeleteShortInline@%
     
    24092359\lstMakeShortInline@%
    24102360\end{cquote}
    2411 While \Celeven has type-generic math (see section~7.25 of the ISO/IEC 9899\cite{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).
     2361While \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).
    24122362For example, it is impossible to overload @atan@ for both one and two arguments;
    2413 instead, the names @atan@ and @atan2@ are required (see Section~\ref{s:NameOverloading}).
    2414 The key observation is that only a restricted set of type-generic macros is provided for a limited set of function names, which do not generalize across the type system, as in \CFA.
     2363instead the names @atan@ and @atan2@ are required (see Section~\ref{s:NameOverloading}).
     2364The 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.
    24152365
    24162366
     
    24182368
    24192369C library @stdlib.h@ provides many general functions.
    2420 \CFA function overloading is used to condense these utility functions.
     2370\CFA function overloading is used to condense these utility functions, \eg:
    24212371\begin{cquote}
    24222372\lstDeleteShortInline@%
     
    24372387\lstMakeShortInline@%
    24382388\end{cquote}
    2439 The result is a significant reduction in names to access the utility functions. \textcolor{blue}{REMOVE ``, as follows.''}
     2389The result is a significant reduction in names to access utility functions, \eg:
    24402390\begin{cquote}
    24412391\lstDeleteShortInline@%
     
    24562406\lstMakeShortInline@%
    24572407\end{cquote}
    2458 In addition, there are polymorphic functions, like @min@ and @max@, that work on any type with operator @?<?@ or @?>?@.
    2459 
    2460 The following shows one example where \CFA \textcolor{blue}{ADD SPACE} \emph{extends} an existing standard C interface to reduce complexity and provide safety.
    2461 C/\Celeven provide a number of complex and overlapping storage-management operations to support the following capabilities.
    2462 \begin{list}{}{\itemsep=0pt\parsep=0pt\labelwidth=0pt\leftmargin\parindent\itemindent-\leftmargin\let\makelabel\descriptionlabel}
     2408In additon, there are polymorphic functions, like @min@ and @max@, that work on any type with operators @?<?@ or @?>?@.
     2409
     2410The following shows one example where \CFA \emph{extends} an existing standard C interface to reduce complexity and provide safety.
     2411C/\Celeven provide a number of complex and overlapping storage-management operation to support the following capabilities:
     2412\begin{description}%[topsep=3pt,itemsep=2pt,parsep=0pt]
    24632413\item[fill]
    24642414an allocation with a specified character.
    24652415\item[resize]
    24662416an existing allocation to decrease or increase its size.
    2467 In either case, new storage may or may not be allocated, and if there is a new allocation, as much data from the existing allocation are copied.
     2417In 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.
    24682418For an increase in storage size, new storage after the copied data may be filled.
    2469 \newpage
    24702419\item[align]
    24712420an allocation on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes.
     
    24732422allocation with a specified number of elements.
    24742423An array may be filled, resized, or aligned.
    2475 \end{list}
    2476 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.
    2477 \CFA storage-management functions extend the C equivalents by overloading, providing shallow type safety, and removing the need to specify the base allocation size.
    2478 Figure~\ref{f:StorageAllocation} contrasts \CFA and C storage allocation performing the same operations with the same type safety.
     2424\end{description}
     2425Table~\ref{t:StorageManagementOperations} shows the capabilities provided by C/\Celeven allocation-functions and how all the capabilities can be combined into two \CFA functions.
     2426\CFA storage-management functions extend the C equivalents by overloading, providing shallow type-safety, and removing the need to specify the base allocation-size.
     2427Figure~\ref{f:StorageAllocation} contrasts \CFA and C storage-allocation performing the same operations with the same type safety.
    24792428
    24802429\begin{table}
    2481 \caption{Storage-management operations}
     2430\caption{Storage-Management Operations}
    24822431\label{t:StorageManagementOperations}
    24832432\centering
    24842433\lstDeleteShortInline@%
    24852434\lstMakeShortInline~%
    2486 \begin{tabular}{@{}rrllll@{}}
    2487 \multicolumn{1}{c}{}&           & \multicolumn{1}{c}{fill}      & resize        & align & array \\
     2435\begin{tabular}{@{}r|r|l|l|l|l@{}}
     2436\multicolumn{1}{c}{}&           & \multicolumn{1}{c|}{fill}     & resize        & align & array \\
     2437\hline
    24882438C               & ~malloc~                      & no                    & no            & no            & no    \\
    24892439                & ~calloc~                      & yes (0 only)  & no            & no            & yes   \\
     
    24912441                & ~memalign~            & no                    & no            & yes           & no    \\
    24922442                & ~posix_memalign~      & no                    & no            & yes           & no    \\
     2443\hline
    24932444C11             & ~aligned_alloc~       & no                    & no            & yes           & no    \\
     2445\hline
    24942446\CFA    & ~alloc~                       & yes/copy              & no/yes        & no            & yes   \\
    24952447                & ~align_alloc~         & yes                   & no            & yes           & yes   \\
     
    25012453\begin{figure}
    25022454\centering
    2503 \fontsize{9bp}{11bp}\selectfont
    25042455\begin{cfa}[aboveskip=0pt,xleftmargin=0pt]
    25052456size_t  dim = 10;                                                       $\C{// array dimension}$
     
    25392490\end{tabular}
    25402491\lstMakeShortInline@%
    2541 \caption{\CFA versus C storage allocation}
     2492\caption{\CFA versus C Storage-Allocation}
    25422493\label{f:StorageAllocation}
    25432494\end{figure}
    25442495
    25452496Variadic @new@ (see Section~\ref{sec:variadic-tuples}) cannot support the same overloading because extra parameters are for initialization.
    2546 Hence, there are @new@ and @anew@ functions for single and array variables, and the fill value is the arguments to the constructor.
     2497Hence, there are @new@ and @anew@ functions for single and array variables, and the fill value is the arguments to the constructor, \eg:
    25472498\begin{cfa}
    25482499struct S { int i, j; };
     
    25512502S * as = anew( dim, 2, 3 );                                     $\C{// each array element initialized to 2, 3}$
    25522503\end{cfa}
    2553 Note that \CC can only initialize array elements via the default constructor.
    2554 
    2555 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.
     2504Note, \CC can only initialize array elements via the default constructor.
     2505
     2506Finally, the \CFA memory-allocator has \newterm{sticky properties} for dynamic storage: fill and alignment are remembered with an object's storage in the heap.
    25562507When a @realloc@ is performed, the sticky properties are respected, so that new storage is correctly aligned and initialized with the fill character.
    25572508
     
    25602511\label{s:IOLibrary}
    25612512
    2562 The goal of \CFA I/O is to simplify the common cases, while fully supporting polymorphism and user-defined types in a consistent way.
     2513The goal of \CFA I/O is to simplify the common cases, while fully supporting polymorphism and user defined types in a consistent way.
    25632514The approach combines ideas from \CC and Python.
    25642515The \CFA header file for the I/O library is @fstream@.
     
    25892540\lstMakeShortInline@%
    25902541\end{cquote}
    2591 The \CFA form has half the characters of the \CC form and is similar to Python I/O with respect to implicit separators.
     2542The \CFA form has half the characters of the \CC form, and is similar to Python I/O with respect to implicit separators.
    25922543Similar simplification occurs for tuple I/O, which prints all tuple values separated by ``\lstinline[showspaces=true]@, @''.
    25932544\begin{cfa}
     
    26222573\lstMakeShortInline@%
    26232574\end{cquote}
    2624 There is a weak similarity between the \CFA logical-or operator and the Shell pipe operator for moving data, where data flow in the correct direction for input but in the opposite direction for output.
     2575There is a weak similarity between the \CFA logical-or operator and the Shell pipe-operator for moving data, where data flows in the correct direction for input but the opposite direction for output.
    26252576\begin{comment}
    26262577The implicit separator character (space/blank) is a separator not a terminator.
     
    26432594\end{itemize}
    26442595\end{comment}
    2645 There are functions to set and get the separator string and manipulators to toggle separation on and off in the middle of output.
    2646 
    2647 
    2648 \subsection{Multiprecision integers}
     2596There are functions to set and get the separator string, and manipulators to toggle separation on and off in the middle of output.
     2597
     2598
     2599\subsection{Multi-precision Integers}
    26492600\label{s:MultiPrecisionIntegers}
    26502601
    2651 \CFA has an interface to the \textcolor{blue}{Q3 CHANGE ``GMP multiprecision'' TO ``GNU multiple precision (GMP)''} signed integers~\cite{GMP}, similar to the \CC interface provided by GMP.
    2652 The \CFA interface wraps GMP functions into operator functions to make programming with multiprecision integers identical to using fixed-sized integers.
    2653 The \CFA type name for multiprecision signed integers is @Int@ and the header file is @gmp@.
    2654 Figure~\ref{f:GMPInterface} shows a multiprecision factorial program contrasting the GMP interface in \CFA and C.
    2655 
    2656 \begin{figure}[b]
     2602\CFA has an interface to the GMP multi-precision signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP.
     2603The \CFA interface wraps GMP functions into operator functions to make programming with multi-precision integers identical to using fixed-sized integers.
     2604The \CFA type name for multi-precision signed-integers is @Int@ and the header file is @gmp@.
     2605Figure~\ref{f:GMPInterface} shows a multi-precision factorial-program contrasting the GMP interface in \CFA and C.
     2606
     2607\begin{figure}
    26572608\centering
    2658 \fontsize{9bp}{11bp}\selectfont
    26592609\lstDeleteShortInline@%
    26602610\begin{tabular}{@{}l@{\hspace{3\parindentlnth}}l@{}}
     
    26872637\end{tabular}
    26882638\lstMakeShortInline@%
    2689 \caption{GMP interface \CFA versus C}
     2639\caption{GMP Interface \CFA versus C}
    26902640\label{f:GMPInterface}
    26912641\end{figure}
    26922642
    26932643
    2694 \vspace{-4pt}
    26952644\section{Polymorphism Evaluation}
    26962645\label{sec:eval}
     
    27012650% Though \CFA provides significant added functionality over C, these features have a low runtime penalty.
    27022651% In fact, it is shown that \CFA's generic programming can enable faster runtime execution than idiomatic @void *@-based C code.
    2703 The experiment is a set of generic-stack microbenchmarks~\cite{CFAStackEvaluation} in C, \CFA, and \CC (see implementations in Appendix~\ref{sec:BenchmarkStackImplementations}).
     2652The experiment is a set of generic-stack micro-benchmarks~\cite{CFAStackEvaluation} in C, \CFA, and \CC (see implementations in Appendix~\ref{sec:BenchmarkStackImplementations}).
    27042653Since all these languages share a subset essentially comprising standard C, maximal-performance benchmarks should show little runtime variance, differing only in length and clarity of source code.
    27052654A more illustrative comparison measures the costs of idiomatic usage of each language's features.
    2706 Figure~\ref{fig:BenchmarkTest} shows the \CFA benchmark tests for a generic stack based on a singly linked list.
     2655Figure~\ref{fig:BenchmarkTest} shows the \CFA benchmark tests for a generic stack based on a singly linked-list.
    27072656The benchmark test is similar for the other languages.
    27082657The experiment uses element types @int@ and @pair(short, char)@, and pushes $N=40M$ elements on a generic stack, copies the stack, clears one of the stacks, and finds the maximum value in the other stack.
    27092658
    27102659\begin{figure}
    2711 \fontsize{9bp}{11bp}\selectfont
    27122660\begin{cfa}[xleftmargin=3\parindentlnth,aboveskip=0pt,belowskip=0pt]
    27132661int main() {
     
    27292677}
    27302678\end{cfa}
    2731 \caption{\protect\CFA benchmark test}
     2679\caption{\protect\CFA Benchmark Test}
    27322680\label{fig:BenchmarkTest}
    2733 \vspace*{-10pt}
    27342681\end{figure}
    27352682
    2736 The structure of each benchmark implemented is C with @void *@-based polymorphism, \CFA with parametric polymorphism, \CC with templates, and \CC using only class inheritance for polymorphism, called \CCV.
     2683The structure of each benchmark implemented is: C with @void *@-based polymorphism, \CFA with parametric polymorphism, \CC with templates, and \CC using only class inheritance for polymorphism, called \CCV.
    27372684The \CCV variant illustrates an alternative object-oriented idiom where all objects inherit from a base @object@ class, mimicking a Java-like interface;
    2738 hence, runtime checks are necessary to safely downcast objects.
    2739 The most notable difference among the implementations is in memory layout of generic types: \CFA and \CC inline the stack and pair elements into corresponding list and pair nodes, whereas C and \CCV lack such capability and, instead, must store generic objects via pointers to separately allocated objects.
    2740 Note that the C benchmark uses unchecked casts as C has no runtime mechanism to perform such checks, whereas \CFA and \CC provide type safety statically.
     2685hence runtime checks are necessary to safely down-cast objects.
     2686The most notable difference among the implementations is in memory layout of generic types: \CFA and \CC inline the stack and pair elements into corresponding list and pair nodes, while C and \CCV lack such a capability and instead must store generic objects via pointers to separately-allocated objects.
     2687Note, the C benchmark uses unchecked casts as C has no runtime mechanism to perform such checks, while \CFA and \CC provide type-safety statically.
    27412688
    27422689Figure~\ref{fig:eval} and Table~\ref{tab:eval} show the results of running the benchmark in Figure~\ref{fig:BenchmarkTest} and its C, \CC, and \CCV equivalents.
    2743 The graph plots the median of five consecutive runs of each program, with an initial warm-up run omitted.
    2744 All code is compiled at \texttt{-O2} by gcc or g++ 6.4.0, with all \CC code compiled as \CCfourteen. \textcolor{blue}{CHANGE ``\CC{}fourteen'' TO ``\CCfourteen''}
    2745 The benchmarks are run on an Ubuntu 16.04 workstation with 16 GB of RAM and a 6-core AMD FX-6300 CPU with 3.5 GHz \textcolor{blue}{REMOVE ``of''} maximum clock frequency.
     2690The graph plots the median of 5 consecutive runs of each program, with an initial warm-up run omitted.
     2691All code is compiled at \texttt{-O2} by gcc or g++ 6.4.0, with all \CC code compiled as \CCfourteen.
     2692The benchmarks are run on an Ubuntu 16.04 workstation with 16 GB of RAM and a 6-core AMD FX-6300 CPU with 3.5 GHz maximum clock frequency.
    27462693
    27472694\begin{figure}
    27482695\centering
    2749 \resizebox{0.7\textwidth}{!}{\input{timing}}
    2750 \caption{Benchmark timing results (smaller is better)}
     2696\input{timing}
     2697\caption{Benchmark Timing Results (smaller is better)}
    27512698\label{fig:eval}
    2752 \vspace*{-10pt}
    27532699\end{figure}
    27542700
    27552701\begin{table}
    2756 \vspace*{-10pt}
    27572702\caption{Properties of benchmark code}
    27582703\label{tab:eval}
    27592704\centering
    2760 \vspace*{-4pt}
    27612705\newcommand{\CT}[1]{\multicolumn{1}{c}{#1}}
    2762 \begin{tabular}{lrrrr}
    2763                                                                         & \CT{C}        & \CT{\CFA}     & \CT{\CC}      & \CT{\CCV}             \\
    2764 maximum memory usage (MB)                       & 10\,001       & 2\,502        & 2\,503        & 11\,253               \\
     2706\begin{tabular}{rrrrr}
     2707                                                                        & \CT{C}        & \CT{\CFA}     & \CT{\CC}      & \CT{\CCV}             \\ \hline
     2708maximum memory usage (MB)                       & 10,001        & 2,502         & 2,503         & 11,253                \\
    27652709source code size (lines)                        & 201           & 191           & 125           & 294                   \\
    27662710redundant type annotations (lines)      & 27            & 0                     & 2                     & 16                    \\
    27672711binary size (KB)                                        & 14            & 257           & 14            & 37                    \\
    27682712\end{tabular}
    2769 \vspace*{-16pt}
    27702713\end{table}
    27712714
    2772 The C and \CCV variants are generally the slowest with the largest memory footprint, due to their less-efficient memory layout and the pointer indirection necessary to implement generic types;
     2715The C and \CCV variants are generally the slowest with the largest memory footprint, because of their less-efficient memory layout and the pointer-indirection necessary to implement generic types;
    27732716this inefficiency is exacerbated by the second level of generic types in the pair benchmarks.
    2774 By contrast, the \CFA and \CC variants run in roughly equivalent time for both the integer and pair because of the equivalent storage layout, with the inlined libraries (\ie no separate compilation) and greater maturity of the \CC compiler contributing to its lead.
    2775 \CCV is slower than C largely due to the cost of runtime type checking of downcasts (implemented with @dynamic_cast@).
     2717By contrast, the \CFA and \CC variants run in roughly equivalent time for both the integer and pair because of equivalent storage layout, with the inlined libraries (\ie no separate compilation) and greater maturity of the \CC compiler contributing to its lead.
     2718\CCV is slower than C largely due to the cost of runtime type-checking of down-casts (implemented with @dynamic_cast@);
    27762719The outlier for \CFA, pop @pair@, results from the complexity of the generated-C polymorphic code.
    27772720The gcc compiler is unable to optimize some dead code and condense nested calls;
     
    27792722Finally, the binary size for \CFA is larger because of static linking with the \CFA libraries.
    27802723
    2781 \CFA is also competitive in terms of source code size, measured as a proxy for programmer effort. The line counts in Table~\ref{tab:eval} include implementations of @pair@ and @stack@ types for all four languages for purposes of direct comparison, although it should be noted that \CFA and \CC have prewritten data structures in their standard libraries that programmers would generally use instead. Use of these standard library types has minimal impact on the performance benchmarks, but shrinks the \CFA and \CC benchmarks to 39 and 42 lines, respectively.
     2724\CFA is also competitive in terms of source code size, measured as a proxy for programmer effort. The line counts in Table~\ref{tab:eval} include implementations of @pair@ and @stack@ types for all four languages for purposes of direct comparison, though it should be noted that \CFA and \CC have pre-written data structures in their standard libraries that programmers would generally use instead. Use of these standard library types has minimal impact on the performance benchmarks, but shrinks the \CFA and \CC benchmarks to 39 and 42 lines, respectively.
    27822725The difference between the \CFA and \CC line counts is primarily declaration duplication to implement separate compilation; a header-only \CFA library would be similar in length to the \CC version.
    2783 On the other hand, C does not have a generic collections library in its standard distribution, resulting in frequent reimplementation of such collection types by C programmers.
    2784 \CCV does not use the \CC standard template library by construction and, in fact, includes the definition of @object@ and wrapper classes for @char@, @short@, and @int@ in its line count, which inflates this count somewhat, as an actual object-oriented language would include these in the standard library;
     2726On the other hand, C does not have a generic collections-library in its standard distribution, resulting in frequent reimplementation of such collection types by C programmers.
     2727\CCV does not use the \CC standard template library by construction, and in fact includes the definition of @object@ and wrapper classes for @char@, @short@, and @int@ in its line count, which inflates this count somewhat, as an actual object-oriented language would include these in the standard library;
    27852728with their omission, the \CCV line count is similar to C.
    27862729We justify the given line count by noting that many object-oriented languages do not allow implementing new interfaces on library types without subclassing or wrapper types, which may be similarly verbose.
    27872730
    2788 Line count is a fairly rough measure of code complexity;
    2789 another important factor is how much type information the programmer must specify manually, especially where that information is not compiler checked.
    2790 Such unchecked type information produces a heavier documentation burden and increased potential for runtime bugs and is much less common in \CFA than C, with its manually specified function pointer arguments and format codes, or \CCV, with its extensive use of un-type-checked downcasts, \eg @object@ to @integer@ when popping a stack.
     2731Line-count is a fairly rough measure of code complexity;
     2732another important factor is how much type information the programmer must specify manually, especially where that information is not compiler-checked.
     2733Such unchecked type information produces a heavier documentation burden and increased potential for runtime bugs, and is much less common in \CFA than C, with its manually specified function pointer arguments and format codes, or \CCV, with its extensive use of un-type-checked downcasts, \eg @object@ to @integer@ when popping a stack.
    27912734To quantify this manual typing, the ``redundant type annotations'' line in Table~\ref{tab:eval} counts the number of lines on which the type of a known variable is respecified, either as a format specifier, explicit downcast, type-specific function, or by name in a @sizeof@, struct literal, or @new@ expression.
    2792 The \CC benchmark uses two redundant type annotations to create a new stack nodes, whereas the C and \CCV benchmarks have several such annotations spread throughout their code.
     2735The \CC benchmark uses two redundant type annotations to create a new stack nodes, while the C and \CCV benchmarks have several such annotations spread throughout their code.
    27932736The \CFA benchmark is able to eliminate all redundant type annotations through use of the polymorphic @alloc@ function discussed in Section~\ref{sec:libraries}.
    27942737
    2795 We conjecture that these results scale across most generic data types as the underlying polymorphism implement is constant.
    2796 
    2797 
    2798 \vspace*{-8pt}
     2738We conjecture these results scale across most generic data-types as the underlying polymorphism implement is constant.
     2739
     2740
    27992741\section{Related Work}
    28002742\label{s:RelatedWork}
     
    28122754\CC provides three disjoint polymorphic extensions to C: overloading, inheritance, and templates.
    28132755The 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.
    2814 In 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.
     2756In 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.
    28152757The key mechanism to support separate compilation is \CFA's \emph{explicit} use of assumed type properties.
    2816 Until \CC concepts~\cite{C++Concepts} are standardized (anticipated for \CCtwenty), \CC provides no way of specifying the requirements of a generic function beyond compilation errors during template expansion;
     2758Until \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;
    28172759furthermore, \CC concepts are restricted to template polymorphism.
    28182760
    28192761Cyclone~\cite{Grossman06} also provides capabilities for polymorphic functions and existential types, similar to \CFA's @forall@ functions and generic types.
    2820 Cyclone existential types can include function pointers in a construct similar to a virtual function table, but these pointers must be explicitly initialized at some point in the code, which is a tedious and potentially error-prone process.
     2762Cyclone existential types can include function pointers in a construct similar to a virtual function-table, but these pointers must be explicitly initialized at some point in the code, a tedious and potentially error-prone process.
    28212763Furthermore, Cyclone's polymorphic functions and types are restricted to abstraction over types with the same layout and calling convention as @void *@, \ie only pointer types and @int@.
    28222764In \CFA terms, all Cyclone polymorphism must be dtype-static.
    28232765While the Cyclone design provides the efficiency benefits discussed in Section~\ref{sec:generic-apps} for dtype-static polymorphism, it is more restrictive than \CFA's general model.
    2824 Smith and Volpano~\cite{Smith98} present Polymorphic C, an ML dialect with polymorphic functions, C-like syntax, and pointer types;
    2825 it lacks many of C's features, most notably structure types, and hence, is not a practical C replacement.
     2766Smith and Volpano~\cite{Smith98} present Polymorphic C, an ML dialect with polymorphic functions, C-like syntax, and pointer types; it lacks many of C's features, however, most notably structure types, and so is not a practical C replacement.
    28262767
    28272768Objective-C~\cite{obj-c-book} is an industrially successful extension to C.
    2828 However, Objective-C is a radical departure from C, using an object-oriented model with message passing.
     2769However, Objective-C is a radical departure from C, using an object-oriented model with message-passing.
    28292770Objective-C did not support type-checked generics until recently \cite{xcode7}, historically using less-efficient runtime checking of object types.
    2830 The GObject~\cite{GObject} framework also adds object-oriented programming with runtime type-checking and reference-counting garbage collection to C;
    2831 these features are more intrusive additions than those provided by \CFA, in addition to the runtime overhead of reference counting.
    2832 Vala~\cite{Vala} compiles to GObject-based C, adding the burden of learning a separate language syntax to the aforementioned demerits of GObject as a modernization path for existing C code bases.
    2833 Java~\cite{Java8} included generic types in Java~5, which are type checked at compilation and type erased at runtime, similar to \CFA's.
    2834 However, in Java, each object carries its own table of method pointers, whereas \CFA passes the method pointers separately to maintain a C-compatible layout.
     2771The GObject~\cite{GObject} framework also adds object-oriented programming with runtime type-checking and reference-counting garbage-collection to C;
     2772these features are more intrusive additions than those provided by \CFA, in addition to the runtime overhead of reference-counting.
     2773Vala~\cite{Vala} compiles to GObject-based C, adding the burden of learning a separate language syntax to the aforementioned demerits of GObject as a modernization path for existing C code-bases.
     2774Java~\cite{Java8} included generic types in Java~5, which are type-checked at compilation and type-erased at runtime, similar to \CFA's.
     2775However, in Java, each object carries its own table of method pointers, while \CFA passes the method pointers separately to maintain a C-compatible layout.
    28352776Java is also a garbage-collected, object-oriented language, with the associated resource usage and C-interoperability burdens.
    28362777
    2837 D~\cite{D}, Go, and Rust~\cite{Rust} are modern compiled languages with abstraction features similar to \CFA traits, \emph{interfaces} in D and Go, and \emph{traits} in Rust.
     2778D~\cite{D}, Go, and Rust~\cite{Rust} are modern, compiled languages with abstraction features similar to \CFA traits, \emph{interfaces} in D and Go and \emph{traits} in Rust.
    28382779However, each language represents a significant departure from C in terms of language model, and none has the same level of compatibility with C as \CFA.
    28392780D and Go are garbage-collected languages, imposing the associated runtime overhead.
    28402781The necessity of accounting for data transfer between managed runtimes and the unmanaged C runtime complicates foreign-function interfaces to C.
    28412782Furthermore, while generic types and functions are available in Go, they are limited to a small fixed set provided by the compiler, with no language facility to define more.
    2842 D restricts garbage collection to its own heap by default, whereas Rust is not garbage collected and, thus, has a lighter-weight runtime more interoperable with C.
     2783D restricts garbage collection to its own heap by default, while Rust is not garbage-collected, and thus has a lighter-weight runtime more interoperable with C.
    28432784Rust also possesses much more powerful abstraction capabilities for writing generic code than Go.
    2844 On the other hand, Rust's borrow checker provides strong safety guarantees but is complex and difficult to learn and imposes a distinctly idiomatic programming style.
     2785On the other hand, Rust's borrow-checker provides strong safety guarantees but is complex and difficult to learn and imposes a distinctly idiomatic programming style.
    28452786\CFA, with its more modest safety features, allows direct ports of C code while maintaining the idiomatic style of the original source.
    28462787
    28472788
    2848 \vspace*{-18pt}
    2849 \subsection{Tuples/variadics}
    2850 
    2851 \vspace*{-5pt}
     2789\subsection{Tuples/Variadics}
     2790
    28522791Many programming languages have some form of tuple construct and/or variadic functions, \eg SETL, C, KW-C, \CC, D, Go, Java, ML, and Scala.
    28532792SETL~\cite{SETL} is a high-level mathematical programming language, with tuples being one of the primary data types.
    28542793Tuples in SETL allow subscripting, dynamic expansion, and multiple assignment.
    2855 C provides variadic functions through @va_list@ objects, but the programmer is responsible for managing the number of arguments and their types;
    2856 thus, the mechanism is type unsafe.
     2794C provides variadic functions through @va_list@ objects, but the programmer is responsible for managing the number of arguments and their types, so the mechanism is type unsafe.
    28572795KW-C~\cite{Buhr94a}, a predecessor of \CFA, introduced tuples to C as an extension of the C syntax, taking much of its inspiration from SETL.
    28582796The main contributions of that work were adding MRVF, tuple mass and multiple assignment, and record-member access.
    2859 \CCeleven introduced @std::tuple@ as a library variadic-template structure.
     2797\CCeleven introduced @std::tuple@ as a library variadic template structure.
    28602798Tuples are a generalization of @std::pair@, in that they allow for arbitrary length, fixed-size aggregation of heterogeneous values.
    28612799Operations include @std::get<N>@ to extract values, @std::tie@ to create a tuple of references used for assignment, and lexicographic comparisons.
    2862 \CCseventeen \textcolor{blue}{CHANGE ``\CC{}seventeen TO ``\CCseventeen''} proposes \emph{structured bindings}~\cite{Sutter15} to eliminate predeclaring variables and the use of @std::tie@ for binding the results.
    2863 This extension requires the use of @auto@ to infer the types of the new variables; hence, complicated expressions with a nonobvious type must be documented with some other mechanism.
     2800\CCseventeen proposes \emph{structured bindings}~\cite{Sutter15} to eliminate pre-declaring variables and use of @std::tie@ for binding the results.
     2801This extension requires the use of @auto@ to infer the types of the new variables, so complicated expressions with a non-obvious type must be documented with some other mechanism.
    28642802Furthermore, structured bindings are not a full replacement for @std::tie@, as it always declares new variables.
    28652803Like \CC, D provides tuples through a library variadic-template structure.
    28662804Go does not have tuples but supports MRVF.
    2867 Java's variadic functions appear similar to C's but are type safe using homogeneous arrays, which are less useful than \CFA's heterogeneously typed variadic functions.
     2805Java's variadic functions appear similar to C's but are type-safe using homogeneous arrays, which are less useful than \CFA's heterogeneously-typed variadic functions.
    28682806Tuples are a fundamental abstraction in most functional programming languages, such as Standard ML~\cite{sml}, Haskell, and Scala~\cite{Scala}, which decompose tuples using pattern matching.
    28692807
    28702808
    2871 \vspace*{-18pt}
    28722809\subsection{C Extensions}
    28732810
    2874 \vspace*{-5pt}
    2875 \CC is the best known C-based language and is similar to \CFA in that both are extensions to C with source and runtime backward compatibility.
    2876 Specific differences between \CFA and \CC have been identified in prior sections, with a final observation that \CFA has equal or fewer tokens to express the same notion in many cases.
     2811\CC is the best known C-based language, and is similar to \CFA in that both are extensions to C with source and runtime backwards compatibility.
     2812Specific difference between \CFA and \CC have been identified in prior sections, with a final observation that \CFA has equal or fewer tokens to express the same notion in many cases.
    28772813The key difference in design philosophies is that \CFA is easier for C programmers to understand by maintaining a procedural paradigm and avoiding complex interactions among extensions.
    28782814\CC, on the other hand, has multiple overlapping features (such as the three forms of polymorphism), many of which have complex interactions with its object-oriented design.
    2879 As a result, \CC has a steep learning curve for even experienced C programmers, especially when attempting to maintain performance equivalent to C legacy code.
    2880 
    2881 There are several other C extension languages with less usage and even more dramatic changes than \CC.
    2882 \mbox{Objective-C} and Cyclone are two other extensions to C with different design goals than \CFA, as discussed above.
     2815As a result, \CC has a steep learning curve for even experienced C programmers, especially when attempting to maintain performance equivalent to C legacy-code.
     2816
     2817There are several other C extension-languages with less usage and even more dramatic changes than \CC.
     2818Objective-C and Cyclone are two other extensions to C with different design goals than \CFA, as discussed above.
    28832819Other languages extend C with more focused features.
    28842820$\mu$\CC~\cite{uC++book}, CUDA~\cite{Nickolls08}, ispc~\cite{Pharr12}, and Sierra~\cite{Leissa14} add concurrent or data-parallel primitives to C or \CC;
    2885 data-parallel features have not yet been added to \CFA, but are easily incorporated within its design, whereas concurrency primitives similar to those in $\mu$\CC have already been added~\cite{Delisle18}.
    2886 Finally, CCured~\cite{Necula02} and Ironclad \CC~\cite{DeLozier13} attempt to provide a more memory-safe C by annotating pointer types with garbage collection information; type-checked polymorphism in \CFA covers several of C's memory-safety issues, but more aggressive approaches such as annotating all pointer types with their nullability or requiring runtime garbage collection are contradictory to \CFA's backward compatibility goals.
     2821data-parallel features have not yet been added to \CFA, but are easily incorporated within its design, while concurrency primitives similar to those in $\mu$\CC have already been added~\cite{Delisle18}.
     2822Finally, CCured~\cite{Necula02} and Ironclad \CC~\cite{DeLozier13} attempt to provide a more memory-safe C by annotating pointer types with garbage collection information; type-checked polymorphism in \CFA covers several of C's memory-safety issues, but more aggressive approaches such as annotating all pointer types with their nullability or requiring runtime garbage collection are contradictory to \CFA's backwards compatibility goals.
    28872823
    28882824
    28892825\section{Conclusion and Future Work}
    28902826
    2891 The goal of \CFA is to provide an evolutionary pathway for large C development environments to be more productive and safer, while respecting the talent and skill of C programmers.
    2892 While 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.
    2893 The 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.
    2894 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.
     2827The goal of \CFA is to provide an evolutionary pathway for large C development-environments to be more productive and safer, while respecting the talent and skill of C programmers.
     2828While 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.
     2829The 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.
     2830The 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.
    28952831The work is a challenging design, engineering, and implementation exercise.
    28962832On the surface, the project may appear as a rehash of similar mechanisms in \CC.
    28972833However, every \CFA feature is different than its \CC counterpart, often with extended functionality, better integration with C and its programmers, and always supporting separate compilation.
    2898 All of these new features are being used by the \CFA development team to build the \CFA runtime system.
     2834All of these new features are being used by the \CFA development-team to build the \CFA runtime-system.
    28992835Finally, we demonstrate that \CFA performance for some idiomatic cases is better than C and close to \CC, showing the design is practically applicable.
    29002836
    29012837While all examples in the paper compile and run, there are ongoing efforts to reduce compilation time, provide better debugging, and add more libraries;
    29022838when this work is complete in early 2019, a public beta release will be available at \url{https://github.com/cforall/cforall}.
    2903 There is also new work on a number of \CFA features, including arrays with size, runtime type information, virtual functions, user-defined conversions, and modules.
    2904 While \CFA polymorphic functions use dynamic virtual dispatch with low runtime overhead (see Section~\ref{sec:eval}), it is not as low as \CC template inlining.
    2905 Hence, it may be beneficial to provide a mechanism for performance-sensitive code.
    2906 Two promising approaches are an @inline@ annotation at polymorphic function call sites to create a template specialization of the function (provided the code is visible) or placing an @inline@ annotation on polymorphic function definitions to instantiate a specialized version for some set of types (\CC template specialization).
    2907  These approaches are not mutually exclusive and allow performance optimizations to be applied only when necessary, without suffering global code bloat.
    2908 In general, we believe separate compilation, producing smaller code, works well with loaded hardware caches, which may offset the benefit of larger inlined code.
     2839There is also new work on a number of \CFA features, including arrays with size, runtime type-information, virtual functions, user-defined conversions, and modules.
     2840While \CFA polymorphic functions use dynamic virtual-dispatch with low runtime overhead (see Section~\ref{sec:eval}), it is not as low as \CC template-inlining.
     2841Hence it may be beneficial to provide a mechanism for performance-sensitive code.
     2842Two promising approaches are an @inline@ annotation at polymorphic function call sites to create a template-specialization of the function (provided the code is visible) or placing an @inline@ annotation on polymorphic function-definitions to instantiate a specialized version for some set of types (\CC template specialization).
     2843 These approaches are not mutually exclusive and allow performance optimizations to be applied only when necessary, without suffering global code-bloat.
     2844In general, we believe separate compilation, producing smaller code, works well with loaded hardware-caches, which may offset the benefit of larger inlined-code.
    29092845
    29102846
    29112847\section{Acknowledgments}
    29122848
    2913 The authors would like to recognize the design assistance of Glen Ditchfield, Richard Bilson, Thierry Delisle, Andrew Beach, and Brice Dobry on the features described in this paper and thank Magnus Madsen for feedback on the writing.
    2914 Funding for this project was provided by Huawei Ltd (\url{http://www.huawei.com}), and Aaron Moss and Peter Buhr were partially funded by the Natural Sciences and Engineering Research Council of Canada.
     2849The authors would like to recognize the design assistance of Glen Ditchfield, Richard Bilson, Thierry Delisle, Andrew Beach and Brice Dobry on the features described in this paper, and thank Magnus Madsen for feedback on the writing.
     2850Funding for this project has been provided by 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.
    29152851
    29162852{%
     
    29952931
    29962932
    2997 \enlargethispage{1000pt}
    29982933\subsection{\CFA}
    29992934\label{s:CforallStack}
     
    30622997
    30632998
    3064 \newpage
    30652999\subsection{\CC}
    30663000
Note: See TracChangeset for help on using the changeset viewer.