source: doc/papers/general/Paper.tex @ 507e7a2

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 507e7a2 was ad4458f, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

Aaron's changes for exceptions

  • Property mode set to 100644
File size: 147.8 KB
Line 
1\documentclass{article}
2
3\usepackage{fullpage}
4\usepackage{epic,eepic}
5\usepackage{xspace,calc,comment}
6\usepackage{upquote}                                            % switch curled `'" to straight
7\usepackage{listings}                                           % format program code
8\usepackage{enumitem}
9\setlist[itemize]{topsep=3pt,itemsep=2pt,parsep=0pt}% global
10\usepackage[flushmargin]{footmisc}                      % support label/reference in footnote
11\usepackage{rotating}
12\usepackage[usenames]{color}
13\usepackage{pslatex}                                            % reduce size of san serif font
14\usepackage[plainpages=false,pdfpagelabels,pdfpagemode=UseNone,pagebackref=true,breaklinks=true,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}
15
16\setlength{\textheight}{9in}
17%\oddsidemargin 0.0in
18\renewcommand{\topfraction}{0.8}                        % float must be greater than X of the page before it is forced onto its own page
19\renewcommand{\bottomfraction}{0.8}                     % float must be greater than X of the page before it is forced onto its own page
20\renewcommand{\floatpagefraction}{0.8}          % float must be greater than X of the page before it is forced onto its own page
21\renewcommand{\textfraction}{0.0}                       % the entire page maybe devoted to floats with no text on the page at all
22
23\lefthyphenmin=4                                                        % hyphen only after 4 characters
24\righthyphenmin=4
25
26% Names used in the document.
27
28\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
29\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
30\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
31\newcommand{\Celeven}{\textrm{C11}\xspace}      % C11 symbolic name
32\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
33\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
34\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
35\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
36\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
37\newcommand{\CCV}{\rm C\kern-.1em\hbox{+\kern-.25em+}obj\xspace} % C++ virtual symbolic name
38\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
39
40%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
42\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
43%\newcommand{\TODO}[1]{\textbf{TODO}: {\itshape #1}} % TODO included
44\newcommand{\TODO}[1]{} % TODO elided
45
46% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
47% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
48% AFTER HYPERREF.
49%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
50\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
51
52\makeatletter
53% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
54% use rather than use \parident directly.
55\newlength{\parindentlnth}
56\setlength{\parindentlnth}{\parindent}
57
58\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
59\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
60
61\newlength{\gcolumnposn}                                        % temporary hack because lstlisting does not handle tabs correctly
62\newlength{\columnposn}
63\setlength{\gcolumnposn}{2.75in}
64\setlength{\columnposn}{\gcolumnposn}
65\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}}
66\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
67
68% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
69% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
70% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
71\newcommand{\newtermFontInline}{\emph}
72\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
73\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
74\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
75
76% Latin abbreviation
77\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
78\newcommand{\EG}{\abbrevFont{e}.\abbrevFont{g}.}
79\newcommand*{\eg}{%
80        \@ifnextchar{,}{\EG}%
81                {\@ifnextchar{:}{\EG}%
82                        {\EG,\xspace}}%
83}%
84\newcommand{\IE}{\abbrevFont{i}.\abbrevFont{e}.}
85\newcommand*{\ie}{%
86        \@ifnextchar{,}{\IE}%
87                {\@ifnextchar{:}{\IE}%
88                        {\IE,\xspace}}%
89}%
90\newcommand{\ETC}{\abbrevFont{etc}}
91\newcommand*{\etc}{%
92        \@ifnextchar{.}{\ETC}%
93        {\ETC.\xspace}%
94}%
95\newcommand{\ETAL}{\abbrevFont{et}~\abbrevFont{al}}
96\newcommand*{\etal}{%
97        \@ifnextchar{.}{\protect\ETAL}%
98                {\protect\ETAL.\xspace}%
99}%
100\newcommand{\VIZ}{\abbrevFont{viz}}
101\newcommand*{\viz}{%
102        \@ifnextchar{.}{\VIZ}%
103                {\VIZ.\xspace}%
104}%
105\makeatother
106
107\newenvironment{cquote}{%
108        \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=3pt\parsep=0pt\leftmargin=\parindentlnth\rightmargin\leftmargin}%
109        \item\relax
110}{%
111        \endlist
112}% cquote
113
114% CFA programming language, based on ANSI C (with some gcc additions)
115\lstdefinelanguage{CFA}[ANSI]{C}{
116        morekeywords={
117                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, _At, __attribute,
118                __attribute__, auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__,
119                __const, __const__, disable, dtype, enable, exception, __extension__, fallthrough, fallthru,
120                finally, forall, ftype, _Generic, _Imaginary, inline, __label__, lvalue, _Noreturn, one_t,
121                otype, restrict, _Static_assert, throw, throwResume, trait, try, ttype, typeof, __typeof,
122                __typeof__, virtual, with, zero_t},
123        morekeywords=[2]{
124                _Atomic, coroutine, is_coroutine, is_monitor, is_thread, monitor, mutex, nomutex, or,
125                resume, suspend, thread, _Thread_local, waitfor, when, yield},
126        moredirectives={defined,include_next}%
127}
128
129\lstset{
130language=CFA,
131columns=fullflexible,
132basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
133stringstyle=\tt,                                                                                % use typewriter font
134tabsize=5,                                                                                              % N space tabbing
135xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
136%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
137escapechar=\$,                                                                                  % LaTeX escape in CFA code
138keepspaces=true,                                                                                %
139showstringspaces=false,                                                                 % do not show spaces with cup
140showlines=true,                                                                                 % show blank lines at end of code
141aboveskip=4pt,                                                                                  % spacing above/below code block
142belowskip=3pt,
143% replace/adjust listing characters that look bad in sanserif
144literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptscriptstyle\land\,$}}1
145        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 {@}{\small{@}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
146        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex\textgreater}2,
147moredelim=**[is][\color{red}]{`}{`},
148}% lstset
149
150% inline code @...@
151\lstMakeShortInline@%
152
153\lstnewenvironment{cfa}[1][]
154{\lstset{#1}}
155{}
156\lstnewenvironment{C++}[1][]                            % use C++ style
157{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
158{}
159
160
161\title{\protect\CFA : Adding Modern Programming Language Features to C}
162
163\author{Aaron Moss, Robert Schluntz, Peter Buhr}
164% \email{a3moss@uwaterloo.ca}
165% \email{rschlunt@uwaterloo.ca}
166% \email{pabuhr@uwaterloo.ca}
167% \affiliation{%
168%       \institution{University of Waterloo}
169%       \department{David R. Cheriton School of Computer Science}
170%       \streetaddress{Davis Centre, University of Waterloo}
171%       \city{Waterloo}
172%       \state{ON}
173%       \postcode{N2L 3G1}
174%       \country{Canada}
175% }
176
177%\terms{generic, tuple, variadic, types}
178%\keywords{generic types, tuple types, variadic types, polymorphic functions, C, Cforall}
179
180\begin{document}
181\maketitle
182
183
184\begin{abstract}
185The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from commercial operating-systems to hobby projects.
186This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
187Nevertheless, C, first standardized over thirty years ago, lacks many features that make programming in more modern languages safer and more productive.
188
189The goal of the \CFA project 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.
190Prior projects have attempted similar goals but failed to honour C programming-style; for instance, adding object-oriented or functional programming with garbage collection is a non-starter for many C developers.
191Specifically, \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.
192This paper presents a quick tour of \CFA features showing how their design avoids shortcomings of similar features in C and other C-like languages.
193Finally, experimental results are presented to validate several of the new features.
194\end{abstract}
195
196
197\section{Introduction}
198
199The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from commercial operating-systems to hobby projects.
200This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
201The TIOBE~\cite{TIOBE} ranks the top 5 most popular programming languages as: Java 16\%, \Textbf{C 7\%}, \Textbf{\CC 5\%}, \Csharp 4\%, Python 4\% = 36\%, where the next 50 languages are less than 3\% each with a long tail.
202The top 3 rankings over the past 30 years are:
203\begin{center}
204\setlength{\tabcolsep}{10pt}
205\lstDeleteShortInline@%
206\begin{tabular}{@{}rccccccc@{}}
207                & 2017  & 2012  & 2007  & 2002  & 1997  & 1992  & 1987          \\ \hline
208Java    & 1             & 1             & 1             & 1             & 12    & -             & -                     \\
209\Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \Textbf{1}& \Textbf{1}    \\
210\CC             & 3             & 3             & 3             & 3             & 2             & 2             & 4                     \\
211\end{tabular}
212\lstMakeShortInline@%
213\end{center}
214Love it or hate it, C is extremely popular, highly used, and one of the few systems languages.
215In many cases, \CC is often used solely as a better C.
216Nonetheless, C, first standardized over thirty years ago, lacks many features that make programming in more modern languages safer and more productive.
217
218\CFA (pronounced ``C-for-all'', and written \CFA or Cforall) is an evolutionary extension of the C programming language that aims to add modern language features to C while maintaining both source compatibility with C and a familiar programming model for programmers.
219The four key design goals for \CFA~\cite{Bilson03} are:
220(1) The behaviour of standard C code must remain the same when translated by a \CFA compiler as when translated by a C compiler;
221(2) Standard C code must be as fast and as small when translated by a \CFA compiler as when translated by a C compiler;
222(3) \CFA code must be at least as portable as standard C code;
223(4) Extensions introduced by \CFA must be translated in the most efficient way possible.
224These 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.
225\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.
226
227\CFA is currently 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).
228Ultimately, a compiler is necessary for advanced features and optimal performance.
229
230This paper identifies shortcomings in existing approaches to generic and variadic data types in C-like languages and presents a design for generic and variadic types avoiding those shortcomings.
231Specifically, 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.
232The new constructs are empirically compared with both standard C and \CC; the results show the new design is comparable in performance.
233
234\section{Polymorphic Functions}
235
236\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}.
237
238\subsection{Name Overloading}
239
240C already has a limited form of ad-hoc polymorphism in the form of its basic arithmetic operators, which apply to a variety of different types using identical syntax.
241\CFA extends the built-in operator overloading by allowing users to define overloads for any function, not just operators, and even any variable;
242Section~\ref{sec:libraries} includes a number of examples of how this overloading simplifies \CFA programming relative to C.
243Code 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.
244As an example:
245
246\begin{cfa}
247int max(int a, int b) { return a < b ? b : a; }  // (1)
248double max(double a, double b) { return a < b ? b : a; }  // (2)
249
250int max = INT_MAX;     // (3)
251double max = DBL_MAX;  // (4)
252
253max(7, -max);   $\C{// uses (1) and (3), by matching int from constant 7}$
254max(max, 3.14); $\C{// uses (2) and (4), by matching double from constant 3.14}$
255
256//max(max, -max);  $\C{// ERROR: ambiguous}$
257int m = max(max, -max); $\C{// uses (1) once and (3) twice, by matching return type}$
258\end{cfa}
259
260\Celeven did add @_Generic@ expressions, which can be used in preprocessor macros to provide a form of ad-hoc polymorphism; however, this polymorphism is both functionally and ergonomically inferior to \CFA name overloading.
261The macro wrapping the generic expression imposes some limitations; as an example, it could not implement the example above, because the variables @max@ would collide with the functions @max@.
262Ergonomic limitations of @_Generic@ include the necessity to put a fixed list of supported types in a single place and manually dispatch to appropriate overloads, as well as possible namespace pollution from the functions dispatched to, which must all have distinct names.
263Though name-overloading removes a major use-case for @_Generic@ expressions, \CFA does implement @_Generic@ for backwards-compatibility purposes. \TODO{actually implement that}
264
265% http://fanf.livejournal.com/144696.html
266% http://www.robertgamble.net/2012/01/c11-generic-selections.html
267% https://abissell.com/2014/01/16/c11s-_generic-keyword-macro-applications-and-performance-impacts/
268
269
270\subsection{\texorpdfstring{\LstKeywordStyle{forall} Functions}{forall Functions}}
271\label{sec:poly-fns}
272
273The 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):
274\begin{cfa}
275`forall( otype T )` T identity( T val ) { return val; }
276int forty_two = identity( 42 );                         $\C{// T is bound to int, forty\_two == 42}$
277\end{cfa}
278The @identity@ function above can be applied to any complete \newterm{object type} (or @otype@).
279The 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.
280The \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.
281If this extra information is not needed, \eg for a pointer, the type parameter can be declared as a \newterm{data type} (or @dtype@).
282
283In \CFA, the polymorphism runtime-cost is spread over each polymorphic call, due to passing more arguments to polymorphic functions;
284the experiments in Section~\ref{sec:eval} show this overhead is similar to \CC virtual-function calls.
285A design advantage is that, unlike \CC template-functions, \CFA polymorphic-functions are compatible with C \emph{separate compilation}, preventing compilation and code bloat.
286
287Since 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.
288For example, the function @twice@ can be defined using the \CFA syntax for operator overloading:
289\begin{cfa}
290forall( otype T `| { T ?+?(T, T); }` ) T twice( T x ) { return x + x; } $\C{// ? denotes operands}$
291int val = twice( twice( 3.7 ) );
292\end{cfa}
293which works for any type @T@ with a matching addition operator.
294The 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@.
295There 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.
296The first approach has a late conversion from @double@ to @int@ on the final assignment, while the second has an eager conversion to @int@.
297\CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach, which corresponds with C-programmer intuition.
298
299Crucial to the design of a new programming language are the libraries to access thousands of external software features.
300Like \CC, \CFA inherits a massive compatible library-base, where other programming languages must rewrite or provide fragile inter-language communication with C.
301A simple example is leveraging the existing type-unsafe (@void *@) C @bsearch@ to binary search a sorted float array:
302\begin{cfa}
303void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
304                                int (* compar)( const void *, const void * ));
305
306int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 :
307                                *(double *)t2 < *(double *)t1 ? 1 : 0; }
308
309double key = 5.0, vals[10] = { /* 10 sorted float values */ };
310double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp );      $\C{// search sorted array}$
311\end{cfa}
312which can be augmented simply with a generalized, type-safe, \CFA-overloaded wrappers:
313\begin{cfa}
314forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) {
315        int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ }
316        return (T *)bsearch( &key, arr, size, sizeof(T), comp ); }
317
318forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) {
319        T * result = bsearch( key, arr, size ); $\C{// call first version}$
320        return result ? result - arr : size; }  $\C{// pointer subtraction includes sizeof(T)}$
321
322double * val = bsearch( 5.0, vals, 10 );        $\C{// selection based on return type}$
323int posn = bsearch( 5.0, vals, 10 );
324\end{cfa}
325The nested function @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
326Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
327As well, an alternate kind of return is made available: position versus pointer to found element.
328\CC's type-system cannot disambiguate between the two versions of @bsearch@ because it does not use the return type in overload resolution, nor can \CC separately compile a templated @bsearch@.
329
330\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}).
331For example, it is possible to write a type-safe \CFA wrapper @malloc@ based on the C @malloc@:
332\begin{cfa}
333forall( dtype T | sized(T) ) T * malloc( void ) { return (T *)malloc( sizeof(T) ); }
334int * ip = malloc();                                            $\C{// select type and size from left-hand side}$
335double * dp = malloc();
336struct S {...} * sp = malloc();
337\end{cfa}
338where the return type supplies the type/size of the allocation, which is impossible in most type systems.
339
340Call-site inferencing and nested functions provide a localized form of inheritance.
341For example, the \CFA @qsort@ only sorts in ascending order using @<@.
342However, it is trivial to locally change this behaviour:
343\begin{cfa}
344forall( otype T | { int ?<?( T, T ); } ) void qsort( const T * arr, size_t size ) { /* use C qsort */ }
345{       int ?<?( double x, double y ) { return x `>` y; }       $\C{// locally override behaviour}$
346        qsort( vals, size );                                    $\C{// descending sort}$
347}
348\end{cfa}
349Within the block, the nested version of @?<?@ performs @?>?@ and this local version overrides the built-in @?<?@ so it is passed to @qsort@.
350Hence, programmers can easily form local environments, adding and modifying appropriate functions, to maximize reuse of other existing functions and types.
351
352
353\subsection{Traits}
354
355\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:
356\begin{cfa}
357trait `summable`( otype T ) {
358        void ?{}( T *, zero_t );                                $\C{// constructor from 0 literal}$
359        T ?+?( T, T );                                                  $\C{// assortment of additions}$
360        T ?+=?( T *, T );
361        T ++?( T * );
362        T ?++( T * ); };
363
364forall( otype T `| summable( T )` ) T sum( T a[$\,$], size_t size ) {  // use trait
365        `T` total = { `0` };                                    $\C{// instantiate T from 0 by calling its constructor}$
366        for ( unsigned int i = 0; i < size; i += 1 ) total `+=` a[i]; $\C{// select appropriate +}$
367        return total; }
368\end{cfa}
369
370In fact, the set of @summable@ trait operators is incomplete, as it is missing assignment for type @T@, but @otype@ is syntactic sugar for the following implicit trait:
371\begin{cfa}
372trait otype( dtype T | sized(T) ) {  // sized is a pseudo-trait for types with known size and alignment
373        void ?{}( T * );                                                $\C{// default constructor}$
374        void ?{}( T *, T );                                             $\C{// copy constructor}$
375        void ?=?( T *, T );                                             $\C{// assignment operator}$
376        void ^?{}( T * ); };                                    $\C{// destructor}$
377\end{cfa}
378Given 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.
379
380In 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.
381Hence, trait names play no part in type equivalence;
382the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
383Nevertheless, trait names form a logical subtype-hierarchy with @dtype@ at the top, where traits often contain overlapping assertions, \eg operator @+@.
384Traits are used like interfaces in Java or abstract base-classes in \CC, but without the nominal inheritance-relationships.
385Instead, 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.
386Hence, 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.
387(Nominal inheritance can be approximated with traits using marker variables or functions, as is done in Go.)
388
389% Nominal inheritance can be simulated with traits using marker variables or functions:
390% \begin{cfa}
391% trait nominal(otype T) {
392%     T is_nominal;
393% };
394% int is_nominal;                                                               $\C{// int now satisfies the nominal trait}$
395% \end{cfa}
396%
397% Traits, however, are significantly more powerful than nominal-inheritance interfaces; most notably, traits may be used to declare a relationship \emph{among} multiple types, a property that may be difficult or impossible to represent in nominal-inheritance type systems:
398% \begin{cfa}
399% trait pointer_like(otype Ptr, otype El) {
400%     lvalue El *?(Ptr);                                                $\C{// Ptr can be dereferenced into a modifiable value of type El}$
401% }
402% struct list {
403%     int value;
404%     list * next;                                                              $\C{// may omit "struct" on type names as in \CC}$
405% };
406% typedef list * list_iterator;
407%
408% lvalue int *?( list_iterator it ) { return it->value; }
409% \end{cfa}
410% In the example above, @(list_iterator, int)@ satisfies @pointer_like@ by the user-defined dereference function, and @(list_iterator, list)@ also satisfies @pointer_like@ by the built-in dereference operator for pointers. Given a declaration @list_iterator it@, @*it@ can be either an @int@ or a @list@, with the meaning disambiguated by context (\eg @int x = *it;@ interprets @*it@ as an @int@, while @(*it).value = 42;@ interprets @*it@ as a @list@).
411% While a nominal-inheritance system with associated types could model one of those two relationships by making @El@ an associated type of @Ptr@ in the @pointer_like@ implementation, few such systems could model both relationships simultaneously.
412
413
414\section{Generic Types}
415
416One of the known shortcomings of standard C is that it does not provide reusable type-safe abstractions for generic data structures and algorithms.
417Broadly speaking, there are three approaches to implement abstract data-structures in C.
418One approach is to write bespoke data-structures for each context in which they are needed.
419While 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.
420A second approach is to use @void *@--based polymorphism, \eg the C standard-library functions @bsearch@ and @qsort@; an approach which does allow reuse of code for common functionality.
421However, 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 would not otherwise be needed.
422A 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.
423Furthermore, writing and using preprocessor macros can be unnatural and inflexible.
424
425\CC, Java, and other languages use \newterm{generic types} to produce type-safe abstract data-types.
426\CFA also implements generic types that integrate efficiently and naturally with the existing polymorphic functions, while retaining backwards compatibility with C and providing separate compilation.
427However, for known concrete parameters, the generic-type definition can be inlined, like \CC templates.
428
429A 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:
430\begin{cfa}
431forall( otype R, otype S ) struct pair {
432        R first;
433        S second;
434};
435forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; }
436forall( dtype F, otype T ) T value_p( pair( F *, T * ) p ) { return * p.second; }
437
438pair( const char *, int ) p = { "magic", 42 };
439int magic = value( p );
440pair( void *, int * ) q = { 0, &p.second };
441magic = value_p( q );
442double d = 1.0;
443pair( double *, double * ) r = { &d, &d };
444d = value_p( r );
445\end{cfa}
446
447\CFA classifies generic types as either \newterm{concrete} or \newterm{dynamic}.
448Concrete types have a fixed memory layout regardless of type parameters, while dynamic types vary in memory layout depending on their type parameters.
449A type may have polymorphic parameters but still be concrete, called \newterm{dtype-static}.
450Polymorphic pointers are an example of dtype-static types, \eg @forall(dtype T) T *@ is a polymorphic type, but for any @T@, @T *@  is a fixed-sized pointer, and therefore, can be represented by a @void *@ in code generation.
451
452\CFA generic types also allow checked argument-constraints.
453For example, the following declaration of a sorted set-type ensures the set key supports equality and relational comparison:
454\begin{cfa}
455forall( otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); } ) struct sorted_set;
456\end{cfa}
457
458
459\subsection{Concrete Generic-Types}
460
461The \CFA translator template-expands concrete generic-types into new structure types, affording maximal inlining.
462To 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.
463A 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.
464For example, the concrete instantiation for @pair( const char *, int )@ is:
465\begin{cfa}
466struct _pair_conc1 {
467        const char * first;
468        int second;
469};
470\end{cfa}
471
472A concrete generic-type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations.
473In the above example, the @pair( F *, T * )@ parameter to @value_p@ is such a type; its expansion is below and it is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate:
474\begin{cfa}
475struct _pair_conc0 {
476        void * first;
477        void * second;
478};
479\end{cfa}
480
481
482\subsection{Dynamic Generic-Types}
483
484Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types.
485As 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.
486Dynamic generic-types also have an \newterm{offset array} containing structure-member offsets.
487A dynamic generic-union needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
488Access 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.
489
490The offset arrays are statically generated where possible.
491If 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;
492if 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.
493As an example, @p.second@ in the @value@ function above is implemented as @*(p + _offsetof_pair[1])@, where @p@ is a @void *@, and @_offsetof_pair@ is the offset array passed into @value@ for @pair( const char *, T )@.
494The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) }@.
495
496In some cases the offset arrays cannot be statically generated.
497For 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.
498\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.
499The \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.
500These 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).
501Results of these layout functions are cached so that they are only computed once per type per function. %, as in the example below for @pair@.
502Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature.
503For instance, a function that strips duplicate values from an unsorted @vector(T)@ would likely have a pointer to the vector as its only explicit parameter, but use some sort of @set(T)@ internally to test for duplicate values.
504This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function.
505
506Whether a type is concrete, dtype-static, or dynamic is decided solely on the @forall@'s type parameters.
507This 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.
508If 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.
509
510
511\subsection{Applications}
512\label{sec:generic-apps}
513
514The reuse of dtype-static structure instantiations enables useful programming patterns at zero runtime cost.
515The most important such pattern is using @forall(dtype T) T *@ as a type-checked replacement for @void *@, \eg creating a lexicographic comparison for pairs of pointers used by @bsearch@ or @qsort@:
516\begin{cfa}
517forall(dtype T) int lexcmp( pair( T *, T * ) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {
518        return cmp( a->first, b->first ) ? : cmp( a->second, b->second );
519}
520\end{cfa}
521Since @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 fields of both pairs and the arguments to the comparison function match in type.
522
523Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \newterm{tag-structures}.
524Sometimes information is only used for type-checking and can be omitted at runtime, \eg:
525\begin{cfa}
526forall(dtype Unit) struct scalar { unsigned long value; };
527struct metres {};
528struct litres {};
529
530forall(dtype U) scalar(U) ?+?( scalar(U) a, scalar(U) b ) {
531        return (scalar(U)){ a.value + b.value };
532}
533scalar(metres) half_marathon = { 21093 };
534scalar(litres) swimming_pool = { 2500000 };
535scalar(metres) marathon = half_marathon + half_marathon;
536scalar(litres) two_pools = swimming_pool + swimming_pool;
537marathon + swimming_pool;                                       $\C{// compilation ERROR}$
538\end{cfa}
539@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 @?+?@.
540These implementations may even be separately compiled, unlike \CC template functions.
541However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume.
542
543
544\section{Tuples}
545\label{sec:tuples}
546
547In many languages, functions can return at most one value;
548however, many operations have multiple outcomes, some exceptional.
549Consider C's @div@ and @remquo@ functions, which return the quotient and remainder for a division of integer and float values, respectively.
550\begin{cfa}
551typedef struct { int quo, rem; } div_t;         $\C{// from include stdlib.h}$
552div_t div( int num, int den );
553double remquo( double num, double den, int * quo );
554div_t qr = div( 13, 5 );                                        $\C{// return quotient/remainder aggregate}$
555int q;
556double r = remquo( 13.5, 5.2, &q );                     $\C{// return remainder, alias quotient}$
557\end{cfa}
558@div@ aggregates the quotient/remainder in a structure, while @remquo@ aliases a parameter to an argument.
559Both approaches are awkward.
560Alternatively, a programming language can directly support returning multiple values, \eg in \CFA:
561\begin{cfa}
562[ int, int ] div( int num, int den );           $\C{// return two integers}$
563[ double, double ] div( double num, double den ); $\C{// return two doubles}$
564int q, r;                                                                       $\C{// overloaded variable names}$
565double q, r;
566[ q, r ] = div( 13, 5 );                                        $\C{// select appropriate div and q, r}$
567[ q, r ] = div( 13.5, 5.2 );                            $\C{// assign into tuple}$
568\end{cfa}
569Clearly, this approach is straightforward to understand and use;
570therefore, why do few programming languages support this obvious feature or provide it awkwardly?
571The answer is that there are complex consequences that cascade through multiple aspects of the language, especially the type-system.
572This section show these consequences and how \CFA handles them.
573
574
575\subsection{Tuple Expressions}
576
577The addition of multiple-return-value functions (MRVF) are useless without a syntax for accepting multiple values at the call-site.
578The simplest mechanism for capturing the return values is variable assignment, allowing the values to be retrieved directly.
579As 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}.
580
581However, 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:
582\begin{cfa}
583printf( "%d %d\n", div( 13, 5 ) );                      $\C{// return values seperated into arguments}$
584\end{cfa}
585Here, the values returned by @div@ are composed with the call to @printf@ by flattening the tuple into separate arguments.
586However, the \CFA type-system must support significantly more complex composition:
587\begin{cfa}
588[ int, int ] foo$\(_1\)$( int );                        $\C{// overloaded foo functions}$
589[ double ] foo$\(_2\)$( int );
590void bar( int, double, double );
591bar( foo( 3 ), foo( 3 ) );
592\end{cfa}
593The 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.
594No combination of @foo@s are an exact match with @bar@'s parameters, so the resolver applies C conversions.
595The 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.
596
597
598\subsection{Tuple Variables}
599
600An important observation from function composition is that new variable names are not required to initialize parameters from an MRVF.
601\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:
602\begin{cfa}
603[ int, int ] qr = div( 13, 5 );                         $\C{// tuple-variable declaration and initialization}$
604[ double, double ] qr = div( 13.5, 5.2 );
605\end{cfa}
606where the tuple variable-name serves the same purpose as the parameter name(s).
607Tuple variables can be composed of any types, except for array types, since array sizes are generally unknown in C.
608
609One way to access the tuple-variable components is with assignment or composition:
610\begin{cfa}
611[ q, r ] = qr;                                                          $\C{// access tuple-variable components}$
612printf( "%d %d\n", qr );
613\end{cfa}
614\CFA also supports \newterm{tuple indexing} to access single components of a tuple expression:
615\begin{cfa}
616[int, int] * p = &qr;                                           $\C{// tuple pointer}$
617int rem = qr`.1`;                                                       $\C{// access remainder}$
618int quo = div( 13, 5 )`.0`;                                     $\C{// access quotient}$
619p`->0` = 5;                                                                     $\C{// change quotient}$
620bar( qr`.1`, qr );                                                      $\C{// pass remainder and quotient/remainder}$
621rem = [div( 13, 5 ), 42]`.0.1`;                         $\C{// access 2nd component of 1st component of tuple expression}$
622\end{cfa}
623
624
625\subsection{Flattening and Restructuring}
626
627In function call contexts, tuples support implicit flattening and restructuring conversions.
628Tuple flattening recursively expands a tuple into the list of its basic components.
629Tuple structuring packages a list of expressions into a value of tuple type, \eg:
630%\lstDeleteShortInline@%
631%\par\smallskip
632%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
633\begin{cfa}
634int f( int, int );
635int g( [int, int] );
636int h( int, [int, int] );
637[int, int] x;
638int y;
639f( x );                 $\C{// flatten}$
640g( y, 10 );             $\C{// structure}$
641h( x, y );              $\C{// flatten and structure}$
642\end{cfa}
643%\end{cfa}
644%&
645%\begin{cfa}
646%\end{tabular}
647%\smallskip\par\noindent
648%\lstMakeShortInline@%
649In the call to @f@, @x@ is implicitly flattened so the components of @x@ are passed as the two arguments.
650In 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@.
651Finally, 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]@.
652The 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.
653
654
655\subsection{Tuple Assignment}
656
657An assignment where the left side is a tuple type is called \newterm{tuple assignment}.
658There 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.
659%\lstDeleteShortInline@%
660%\par\smallskip
661%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
662\begin{cfa}
663int x = 10;
664double y = 3.5;
665[int, double] z;
666z = [x, y];                                                                     $\C{// multiple assignment}$
667[x, y] = z;                                                                     $\C{// multiple assignment}$
668z = 10;                                                                         $\C{// mass assignment}$
669[y, x] = 3.14;                                                          $\C{// mass assignment}$
670\end{cfa}
671%\end{cfa}
672%&
673%\begin{cfa}
674%\end{tabular}
675%\smallskip\par\noindent
676%\lstMakeShortInline@%
677Both kinds of tuple assignment have parallel semantics, so that each value on the left and right side is evaluated before any assignments occur.
678As 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]@.
679This 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.
680For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, yielding @y == 3.14@ and @x == 3@;
681whereas, C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, yielding @3@ in @y@ and @x@.
682Finally, 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.
683This example shows mass, multiple, and cascading assignment used in one expression:
684\begin{cfa}
685void f( [int, int] );
686f( [x, y] = z = 1.5 );                                          $\C{// assignments in parameter list}$
687\end{cfa}
688
689
690\subsection{Member Access}
691
692It is also possible to access multiple fields from a single expression using a \newterm{member-access}.
693The result is a single tuple-valued expression whose type is the tuple of the types of the members, \eg:
694\begin{cfa}
695struct S { int x; double y; char * z; } s;
696s.[x, y, z] = 0;
697\end{cfa}
698Here, the mass assignment sets all members of @s@ to zero.
699Since tuple-index expressions are a form of member-access expression, it is possible to use tuple-index expressions in conjunction with member tuple expressions to manually restructure a tuple (\eg rearrange, drop, and duplicate components).
700%\lstDeleteShortInline@%
701%\par\smallskip
702%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
703\begin{cfa}
704[int, int, long, double] x;
705void f( double, long );
706x.[0, 1] = x.[1, 0];                                            $\C{// rearrange: [x.0, x.1] = [x.1, x.0]}$
707f( x.[0, 3] );                                                          $\C{// drop: f(x.0, x.3)}$
708[int, int, int] y = x.[2, 0, 2];                        $\C{// duplicate: [y.0, y.1, y.2] = [x.2, x.0.x.2]}$
709\end{cfa}
710%\end{cfa}
711%&
712%\begin{cfa}
713%\end{tabular}
714%\smallskip\par\noindent
715%\lstMakeShortInline@%
716It is also possible for a member access to contain other member accesses, \eg:
717\begin{cfa}
718struct A { double i; int j; };
719struct B { int * k; short l; };
720struct C { int x; A y; B z; } v;
721v.[x, y.[i, j], z.k];                                           $\C{// [v.x, [v.y.i, v.y.j], v.z.k]}$
722\end{cfa}
723
724
725\begin{comment}
726\subsection{Casting}
727
728In C, the cast operator is used to explicitly convert between types.
729In \CFA, the cast operator has a secondary use as type ascription.
730That is, a cast can be used to select the type of an expression when it is ambiguous, as in the call to an overloaded function:
731\begin{cfa}
732int f();     // (1)
733double f()// (2)
734
735f();       // ambiguous - (1),(2) both equally viable
736(int)f()// choose (2)
737\end{cfa}
738
739Since casting is a fundamental operation in \CFA, casts should be given a meaningful interpretation in the context of tuples.
740Taking a look at standard C provides some guidance with respect to the way casts should work with tuples:
741\begin{cfa}
742int f();
743void g();
744
745(void)f()// (1)
746(int)g()// (2)
747\end{cfa}
748In C, (1) is a valid cast, which calls @f@ and discards its result.
749On the other hand, (2) is invalid, because @g@ does not produce a result, so requesting an @int@ to materialize from nothing is nonsensical.
750Generalizing these principles, any cast wherein the number of components increases as a result of the cast is invalid, while casts that have the same or fewer number of components may be valid.
751
752Formally, a cast to tuple type is valid when $T_n \leq S_m$, where $T_n$ is the number of components in the target type and $S_m$ is the number of components in the source type, and for each $i$ in $[0, n)$, $S_i$ can be cast to $T_i$.
753Excess elements ($S_j$ for all $j$ in $[n, m)$) are evaluated, but their values are discarded so that they are not included in the result expression.
754This approach follows naturally from the way that a cast to @void@ works in C.
755
756For example, in
757\begin{cfa}
758[int, int, int] f();
759[int, [int, int], int] g();
760
761([int, double])f();           $\C{// (1)}$
762([int, int, int])g();         $\C{// (2)}$
763([void, [int, int]])g();      $\C{// (3)}$
764([int, int, int, int])g();    $\C{// (4)}$
765([int, [int, int, int]])g()$\C{// (5)}$
766\end{cfa}
767
768(1) discards the last element of the return value and converts the second element to @double@.
769Since @int@ is effectively a 1-element tuple, (2) discards the second component of the second element of the return value of @g@.
770If @g@ is free of side effects, this expression is equivalent to @[(int)(g().0), (int)(g().1.0), (int)(g().2)]@.
771Since @void@ is effectively a 0-element tuple, (3) discards the first and third return values, which is effectively equivalent to @[(int)(g().1.0), (int)(g().1.1)]@).
772
773Note that a cast is not a function call in \CFA, so flattening and structuring conversions do not occur for cast expressions\footnote{User-defined conversions have been considered, but for compatibility with C and the existing use of casts as type ascription, any future design for such conversions would require more precise matching of types than allowed for function arguments and parameters.}.
774As such, (4) is invalid because the cast target type contains 4 components, while the source type contains only 3.
775Similarly, (5) is invalid because the cast @([int, int, int])(g().1)@ is invalid.
776That is, it is invalid to cast @[int, int]@ to @[int, int, int]@.
777\end{comment}
778
779
780\subsection{Polymorphism}
781
782Tuples also integrate with \CFA polymorphism as a kind of generic type.
783Due 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:
784\begin{cfa}
785forall(otype T, dtype U) void f( T x, U * y );
786f( [5, "hello"] );
787\end{cfa}
788where @[5, "hello"]@ is flattened, giving argument list @5, "hello"@, and @T@ binds to @int@ and @U@ binds to @const char@.
789Tuples, however, may contain polymorphic components.
790For example, a plus operator can be written to add two triples together.
791\begin{cfa}
792forall(otype T | { T ?+?( T, T ); }) [T, T, T] ?+?( [T, T, T] x, [T, T, T] y ) {
793        return [x.0 + y.0, x.1 + y.1, x.2 + y.2];
794}
795[int, int, int] x;
796int i1, i2, i3;
797[i1, i2, i3] = x + ([10, 20, 30]);
798\end{cfa}
799
800Flattening and restructuring conversions are also applied to tuple types in polymorphic type assertions.
801\begin{cfa}
802int f( [int, double], double );
803forall(otype T, otype U | { T f( T, U, U ); }) void g( T, U );
804g( 5, 10.21 );
805\end{cfa}
806Hence, function parameter and return lists are flattened for the purposes of type unification allowing the example to pass expression resolution.
807This relaxation is possible by extending the thunk scheme described by Bilson~\cite{Bilson03}.
808Whenever a candidate's parameter structure does not exactly match the formal parameter's structure, a thunk is generated to specialize calls to the actual function:
809\begin{cfa}
810int _thunk( int _p0, double _p1, double _p2 ) { return f( [_p0, _p1], _p2 ); }
811\end{cfa}
812so the thunk provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
813These thunks take advantage of gcc C nested-functions to produce closures that have the usual function-pointer signature.
814
815
816\subsection{Variadic Tuples}
817\label{sec:variadic-tuples}
818
819To define variadic functions, \CFA adds a new kind of type parameter, @ttype@ (tuple type).
820Matching against a @ttype@ parameter consumes all remaining argument components and packages them into a tuple, binding to the resulting tuple of types.
821In 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.
822As such, @ttype@ variables are also called \newterm{argument packs}.
823
824Like variadic templates, the main way to manipulate @ttype@ polymorphic functions is via recursion.
825Since nothing is known about a parameter pack by default, assertion parameters are key to doing anything meaningful.
826Unlike variadic templates, @ttype@ polymorphic functions can be separately compiled.
827For example, a generalized @sum@ function written using @ttype@:
828\begin{cfa}
829int sum$\(_0\)$() { return 0; }
830forall(ttype Params | { int sum( Params ); } ) int sum$\(_1\)$( int x, Params rest ) {
831        return x + sum( rest );
832}
833sum( 10, 20, 30 );
834\end{cfa}
835Since @sum@\(_0\) does not accept any arguments, it is not a valid candidate function for the call @sum(10, 20, 30)@.
836In 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]@.
837The process continues unitl @Params@ is bound to @[]@, requiring an assertion @int sum()@, which matches @sum@\(_0\) and terminates the recursion.
838Effectively, 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))@.
839
840It is reasonable to take the @sum@ function a step further to enforce a minimum number of arguments:
841\begin{cfa}
842int sum( int x, int y ) { return x + y; }
843forall(ttype Params | { int sum( int, Params ); } ) int sum( int x, int y, Params rest ) {
844        return sum( x + y, rest );
845}
846\end{cfa}
847One more step permits the summation of any summable type with all arguments of the same type:
848\begin{cfa}
849trait summable(otype T) {
850        T ?+?( T, T );
851};
852forall(otype R | summable( R ) ) R sum( R x, R y ) {
853        return x + y;
854}
855forall(otype R, ttype Params | summable(R) | { R sum(R, Params); } ) R sum(R x, R y, Params rest) {
856        return sum( x + y, rest );
857}
858\end{cfa}
859Unlike C variadic functions, it is unnecessary to hard code the number and expected types.
860Furthermore, this code is extendable for any user-defined type with a @?+?@ operator.
861Summing arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators.
862
863It is also possible to write a type-safe variadic print function to replace @printf@:
864\begin{cfa}
865struct S { int x, y; };
866forall(otype T, ttype Params | { void print(T); void print(Params); }) void print(T arg, Params rest) {
867        print(arg);  print(rest);
868}
869void print( char * x ) { printf( "%s", x ); }
870void print( int x ) { printf( "%d", x ); }
871void print( S s ) { print( "{ ", s.x, ",", s.y, " }" ); }
872print( "s = ", (S){ 1, 2 }, "\n" );
873\end{cfa}
874This example showcases a variadic-template-like decomposition of the provided argument list.
875The individual @print@ functions allow printing a single element of a type.
876The polymorphic @print@ allows printing any list of types, where as each individual type has a @print@ function.
877The individual print functions can be used to build up more complicated @print@ functions, such as @S@, which cannot be done with @printf@ in C.
878
879Finally, it is possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions.
880For example, it is possible to write @new@ as a library function:
881\begin{cfa}
882forall( otype R, otype S ) void ?{}( pair(R, S) *, R, S );
883forall( dtype T, ttype Params | sized(T) | { void ?{}( T *, Params ); } ) T * new( Params p ) {
884        return ((T *)malloc()){ p };                    $\C{// construct into result of malloc}$
885}
886pair( int, char ) * x = new( 42, '!' );
887\end{cfa}
888The @new@ function provides the combination of type-safe @malloc@ with a \CFA constructor call, making it impossible to forget constructing dynamically allocated objects.
889This function provides the type-safety of @new@ in \CC, without the need to specify the allocated type again, thanks to return-type inference.
890
891
892\subsection{Implementation}
893
894Tuples are implemented in the \CFA translator via a transformation into \newterm{generic types}.
895For each $N$, the first time an $N$-tuple is seen in a scope a generic type with $N$ type parameters is generated, \eg:
896\begin{cfa}
897[int, int] f() {
898        [double, double] x;
899        [int, double, int] y;
900}
901\end{cfa}
902is transformed into:
903\begin{cfa}
904forall(dtype T0, dtype T1 | sized(T0) | sized(T1)) struct _tuple2 {
905        T0 field_0;                                                             $\C{// generated before the first 2-tuple}$
906        T1 field_1;
907};
908_tuple2(int, int) f() {
909        _tuple2(double, double) x;
910        forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2)) struct _tuple3 {
911                T0 field_0;                                                     $\C{// generated before the first 3-tuple}$
912                T1 field_1;
913                T2 field_2;
914        };
915        _tuple3(int, double, int) y;
916}
917\end{cfa}
918\begin{sloppypar}
919Tuple expressions are then simply converted directly into compound literals, \eg @[5, 'x', 1.24]@ becomes @(_tuple3(int, char, double)){ 5, 'x', 1.24 }@.
920\end{sloppypar}
921
922\begin{comment}
923Since tuples are essentially structures, tuple indexing expressions are just field accesses:
924\begin{cfa}
925void f(int, [double, char]);
926[int, double] x;
927
928x.0+x.1;
929printf("%d %g\n", x);
930f(x, 'z');
931\end{cfa}
932Is transformed into:
933\begin{cfa}
934void f(int, _tuple2(double, char));
935_tuple2(int, double) x;
936
937x.field_0+x.field_1;
938printf("%d %g\n", x.field_0, x.field_1);
939f(x.field_0, (_tuple2){ x.field_1, 'z' });
940\end{cfa}
941Note that due to flattening, @x@ used in the argument position is converted into the list of its fields.
942In the call to @f@, the second and third argument components are structured into a tuple argument.
943Similarly, tuple member expressions are recursively expanded into a list of member access expressions.
944
945Expressions that may contain side effects are made into \newterm{unique expressions} before being expanded by the flattening conversion.
946Each unique expression is assigned an identifier and is guaranteed to be executed exactly once:
947\begin{cfa}
948void g(int, double);
949[int, double] h();
950g(h());
951\end{cfa}
952Internally, this expression is converted to two variables and an expression:
953\begin{cfa}
954void g(int, double);
955[int, double] h();
956
957_Bool _unq0_finished_ = 0;
958[int, double] _unq0;
959g(
960        (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).0,
961        (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).1,
962);
963\end{cfa}
964Since argument evaluation order is not specified by the C programming language, this scheme is built to work regardless of evaluation order.
965The first time a unique expression is executed, the actual expression is evaluated and the accompanying boolean is set to true.
966Every subsequent evaluation of the unique expression then results in an access to the stored result of the actual expression.
967Tuple member expressions also take advantage of unique expressions in the case of possible impurity.
968
969Currently, the \CFA translator has a very broad, imprecise definition of impurity, where any function call is assumed to be impure.
970This notion could be made more precise for certain intrinsic, auto-generated, and builtin functions, and could analyze function bodies when they are available to recursively detect impurity, to eliminate some unique expressions.
971
972The various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions.
973A variable is generated to store the value produced by a statement expression, since its fields 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.
974The 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.
975However, 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.
976\end{comment}
977
978
979\section{Control Structures}
980
981\CFA identifies missing and problematic control structures in C, and extends and modifies these control structures to increase functionality and safety.
982
983
984\subsection{\texorpdfstring{Labelled \LstKeywordStyle{continue} / \LstKeywordStyle{break}}{Labelled continue / break}}
985
986While C provides @continue@ and @break@ statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
987Unfortunately, this restriction forces programmers to use @goto@ to achieve the equivalent control-flow for more than one level of nesting.
988To 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.
989For both @continue@ and @break@, the target label must be directly associated with a @for@, @while@ or @do@ statement;
990for @break@, the target label can also be associated with a @switch@, @if@ or compound (@{}@) statement.
991Figure~\ref{f:MultiLevelExit} shows @continue@ and @break@ indicating the specific control structure, and the corresponding C program using only @goto@ and labels.
992The innermost loop has 7 exit points, which cause continuation or termination of one or more of the 7 nested control-structures.
993
994\begin{figure}
995\lstDeleteShortInline@%
996\begin{tabular}{@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
997\multicolumn{1}{@{\hspace{\parindentlnth}}c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}   & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
998\begin{cfa}
999`LC:` {
1000        ... $declarations$ ...
1001        `LS:` switch ( ... ) {
1002          case 3:
1003                `LIF:` if ( ... ) {
1004                        `LF:` for ( ... ) {
1005                                `LW:` while ( ... ) {
1006                                        ... break `LC`; ...
1007                                        ... break `LS`; ...
1008                                        ... break `LIF`; ...
1009                                        ... continue `LF;` ...
1010                                        ... break `LF`; ...
1011                                        ... continue `LW`; ...
1012                                        ... break `LW`; ...
1013                                } // while
1014                        } // for
1015                } else {
1016                        ... break `LIF`; ...
1017                } // if
1018        } // switch
1019} // compound
1020\end{cfa}
1021&
1022\begin{cfa}
1023{
1024        ... $declarations$ ...
1025        switch ( ... ) {
1026          case 3:
1027                if ( ... ) {
1028                        for ( ... ) {
1029                                while ( ... ) {
1030                                        ... goto `LC`; ...
1031                                        ... goto `LS`; ...
1032                                        ... goto `LIF`; ...
1033                                        ... goto `LFC`; ...
1034                                        ... goto `LFB`; ...
1035                                        ... goto `LWC`; ...
1036                                        ... goto `LWB`; ...
1037                                  `LWC`: ; } `LWB:` ;
1038                          `LFC:` ; } `LFB:` ;
1039                } else {
1040                        ... goto `LIF`; ...
1041                } `L3:` ;
1042        } `LS:` ;
1043} `LC:` ;
1044\end{cfa}
1045&
1046\begin{cfa}
1047
1048
1049
1050
1051
1052
1053
1054// terminate compound
1055// terminate switch
1056// terminate if
1057// continue loop
1058// terminate loop
1059// continue loop
1060// terminate loop
1061
1062
1063
1064// terminate if
1065
1066
1067
1068\end{cfa}
1069\end{tabular}
1070\lstMakeShortInline@%
1071\caption{Multi-level Exit}
1072\label{f:MultiLevelExit}
1073\end{figure}
1074
1075Both labelled @continue@ and @break@ are a @goto@ restricted in the following ways:
1076\begin{itemize}
1077\item
1078They cannot create a loop, which means only the looping constructs cause looping.
1079This restriction means all situations resulting in repeated execution are clearly delineated.
1080\item
1081They cannot branch into a control structure.
1082This restriction prevents missing declarations and/or initializations at the start of a control structure resulting in undefined behaviour.
1083\end{itemize}
1084The 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.
1085Furthermore, 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.
1086With @goto@, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader.
1087Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs.
1088The implicit targets of the current @continue@ and @break@, \ie the closest enclosing loop or @switch@, change as certain constructs are added or removed.
1089
1090
1091\subsection{\texorpdfstring{Enhanced \LstKeywordStyle{switch} Statement}{Enhanced switch Statement}}
1092
1093There 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.
1094
1095C 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.}.
1096\CFA provides a shorthand for a non-contiguous list:
1097\begin{cquote}
1098\lstDeleteShortInline@%
1099\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1100\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1101\begin{cfa}
1102case 2, 10, 34, 42:
1103\end{cfa}
1104&
1105\begin{cfa}
1106case 2: case 10: case 34: case 42:
1107\end{cfa}
1108\end{tabular}
1109\lstMakeShortInline@%
1110\end{cquote}
1111for a contiguous list:\footnote{gcc provides the same mechanism with awkward syntax, \lstinline@2 ... 42@, where spaces are required around the ellipse.}
1112\begin{cquote}
1113\lstDeleteShortInline@%
1114\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1115\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1116\begin{cfa}
1117case 2~42:
1118\end{cfa}
1119&
1120\begin{cfa}
1121case 2: case 3: ... case 41: case 42:
1122\end{cfa}
1123\end{tabular}
1124\lstMakeShortInline@%
1125\end{cquote}
1126and a combination:
1127\begin{cfa}
1128case -12~-4, -1~5, 14~21, 34~42:
1129\end{cfa}
1130
1131C allows placement of @case@ clauses \emph{within} statements nested in the @switch@ body (see Duff's device~\cite{Duff83});
1132\begin{cfa}
1133switch ( i ) {
1134  case 0:
1135        for ( int i = 0; i < 10; i += 1 ) {
1136                ...
1137  `case 1:`             // no initialization of loop index
1138                ...
1139        }
1140}
1141\end{cfa}
1142\CFA precludes this form of transfer into a control structure because it causes undefined behaviour, especially with respect to missed initialization, and provides very limited functionality.
1143
1144C allows placement of declaration within the @switch@ body and unreachable code at the start, resulting in undefined behaviour:
1145\begin{cfa}
1146switch ( x ) {
1147        `int y = 1;`                            $\C{// unreachable initialization}$
1148        `x = 7;`                                        $\C{// unreachable code without label/branch}$
1149  case 0:
1150        ...
1151        `int z = 0;`                            $\C{// unreachable initialization, cannot appear after case}$
1152        z = 2;
1153  case 1:
1154        `x = z;`                                        $\C{// without fall through, z is undefined}$
1155}
1156\end{cfa}
1157\CFA allows the declaration of local variables, \eg @y@, at the start of the @switch@ with scope across the entire @switch@ body, \ie all @case@ clauses.
1158\CFA disallows the declaration of local variable, \eg @z@, directly within the @switch@ body, because a declaration cannot occur immediately after a @case@ since a label can only be attached to a statement, and the use of @z@ is undefined in @case 1@ as neither storage allocation nor initialization may have occurred.
1159
1160C @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};
1161@case@ clauses are made disjoint by the @break@ statement.
1162While the ability to fall through \emph{is} a useful form of control flow, it does not match well with programmer intuition, resulting in many errors from missing @break@ statements.
1163For backwards compatibility, \CFA provides a \emph{new} control structure, @choose@, which mimics @switch@, but reverses the meaning of fall through:
1164\begin{cquote}
1165\lstDeleteShortInline@%
1166\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1167\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1168\begin{cfa}
1169`choose` ( day ) {
1170  case Mon~Thu:  // program
1171
1172  case Fri:  // program
1173        wallet += pay;
1174        `fallthrough;`
1175  case Sat:  // party
1176        wallet -= party;
1177
1178  case Sun:  // rest
1179
1180  default:  // error
1181}
1182\end{cfa}
1183&
1184\begin{cfa}
1185switch ( day ) {
1186  case Mon: case Tue: case Wed: case Thu:  // program
1187        `break;`
1188  case Fri:  // program
1189        wallet += pay;
1190
1191  case Sat:  // party
1192        wallet -= party;
1193        `break;`
1194  case Sun:  // rest
1195        `break;`
1196  default:  // error
1197}
1198\end{cfa}
1199\end{tabular}
1200\lstMakeShortInline@%
1201\end{cquote}
1202Collectively, these enhancements reduce programmer burden and increase readability and safety.
1203
1204\begin{comment}
1205Forgotten @break@ statements at the end of @switch@ cases are a persistent sort of programmer error in C, and the @break@ statements themselves introduce visual clutter and an un-C-like keyword-based block delimiter.
1206\CFA addresses this error by introducing a @choose@ statement, which works identically to a @switch@ except that its default end-of-case behaviour is to break rather than to fall through for all non-empty cases.
1207Since empty cases like @case 7:@ in @case 7: case 11:@ still have fall-through semantics and explicit @break@ is still allowed at the end of a @choose@ case, many idiomatic uses of @switch@ in standard C can be converted to @choose@ statements by simply changing the keyword.
1208Where fall-through is desired for a non-empty case, it can be specified with the new @fallthrough@ statement, making @choose@ equivalently powerful to @switch@, but more concise in the common case where most non-empty cases end with a @break@ statement, as in the example below:
1209
1210\begin{cfa}
1211choose( i ) {
1212        case 2:
1213                printf("even ");
1214                fallthrough;
1215        case 3: case 5: case 7:
1216                printf("small prime\n");
1217        case 4,6,8,9:
1218                printf("small composite\n");
1219        case 13~19:
1220                printf("teen\n");
1221        default:
1222                printf("something else\n");
1223}
1224\end{cfa}
1225\end{comment}
1226
1227
1228\subsection{\texorpdfstring{\LstKeywordStyle{with} Clause / Statement}{with Clause / Statement}}
1229\label{s:WithClauseStatement}
1230
1231Grouping heterogeneous data into \newterm{aggregate}s (structure/union) is a common programming practice, and an aggregate can be further organized into more complex structures, such as arrays and containers:
1232\begin{cfa}
1233struct S {                                                                      $\C{// aggregate}$
1234        char c;                                                                 $\C{// fields}$
1235        int i;
1236        double d;
1237};
1238S s, as[10];
1239\end{cfa}
1240However, routines manipulating aggregates must repeat the aggregate name to access its containing fields:
1241\begin{cfa}
1242void f( S s ) {
1243        `s.`c; `s.`i; `s.`d;                                    $\C{// access containing fields}$
1244}
1245\end{cfa}
1246which extends to multiple levels of qualification for nested aggregates.
1247A similar situation occurs in object-oriented programming, \eg \CC:
1248\begin{C++}
1249class C {
1250        char c;                                                                 $\C{// fields}$
1251        int i;
1252        double d;
1253        int f() {                                                               $\C{// implicit ``this'' aggregate}$
1254                `this->`c; `this->`i; `this->`d;        $\C{// access containing fields}$
1255        }
1256}
1257\end{C++}
1258Object-oriented nesting of member routines in a \lstinline[language=C++]@class@ allows eliding \lstinline[language=C++]@this->@ because of lexical scoping.
1259However, for other aggregate parameters, qualification is necessary:
1260\begin{cfa}
1261struct T { double m, n; };
1262int C::f( T & t ) {                                                     $\C{// multiple aggregate parameters}$
1263        c; i; d;                                                                $\C{\color{red}// this-\textgreater.c, this-\textgreater.i, this-\textgreater.d}$
1264        `t.`m; `t.`n;                                                   $\C{// must qualify}$
1265}
1266\end{cfa}
1267
1268To simplify the programmer experience, \CFA provides a @with@ statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate qualification to fields by opening a scope containing the field identifiers.
1269Hence, the qualified fields become variables with the side-effect that it is easier to optimizing field references in a block.
1270\begin{cfa}
1271void f( S & this ) `with ( this )` {            $\C{// with statement}$
1272        c; i; d;                                                                $\C{\color{red}// this.c, this.i, this.d}$
1273}
1274\end{cfa}
1275with the generality of opening multiple aggregate-parameters:
1276\begin{cfa}
1277int f( S & s, T & t ) `with ( s, t )` {         $\C{// multiple aggregate parameters}$
1278        c; i; d;                                                                $\C{\color{red}// s.c, s.i, s.d}$
1279        m; n;                                                                   $\C{\color{red}// t.m, t.n}$
1280}
1281\end{cfa}
1282
1283In detail, the @with@ statement has the form:
1284\begin{cfa}
1285$\emph{with-statement}$:
1286        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
1287\end{cfa}
1288and may appear as the body of a routine or nested within a routine body.
1289Each expression in the expression-list provides a type and object.
1290The type must be an aggregate type.
1291(Enumerations are already opened.)
1292The object is the implicit qualifier for the open structure-fields.
1293
1294All expressions in the expression list are open in parallel within the compound statement.
1295This semantic is different from Pascal, which nests the openings from left to right.
1296The difference between parallel and nesting occurs for fields with the same name and type:
1297\begin{cfa}
1298struct S { int `i`; int j; double m; } s, w;
1299struct T { int `i`; int k; int m; } t, w;
1300with ( s, t ) {
1301        j + k;                                                                  $\C{// unambiguous, s.j + t.k}$
1302        m = 5.0;                                                                $\C{// unambiguous, t.m = 5.0}$
1303        m = 1;                                                                  $\C{// unambiguous, s.m = 1}$
1304        int a = m;                                                              $\C{// unambiguous, a = s.i }$
1305        double b = m;                                                   $\C{// unambiguous, b = t.m}$
1306        int c = s.i + t.i;                                              $\C{// unambiguous, qualification}$
1307        (double)m;                                                              $\C{// unambiguous, cast}$
1308}
1309\end{cfa}
1310For parallel semantics, both @s.i@ and @t.i@ are visible, so @i@ is ambiguous without qualification;
1311for nested semantics, @t.i@ hides @s.i@, so @i@ implies @t.i@.
1312\CFA's ability to overload variables means fields with the same name but different types are automatically disambiguated, eliminating most qualification when opening multiple aggregates.
1313Qualification or a cast is used to disambiguate.
1314
1315There is an interesting problem between parameters and the routine @with@, \eg:
1316\begin{cfa}
1317void ?{}( S & s, int i ) with ( s ) {           $\C{// constructor}$
1318        `s.i = i;`  j = 3;  m = 5.5;                    $\C{// initialize fields}$
1319}
1320\end{cfa}
1321Here, the assignment @s.i = i@ means @s.i = s.i@, which is meaningless, and there is no mechanism to qualify the parameter @i@, making the assignment impossible using the routine @with@.
1322To solve this problem, parameters are treated like an initialized aggregate:
1323\begin{cfa}
1324struct Params {
1325        S & s;
1326        int i;
1327} params;
1328\end{cfa}
1329and implicitly opened \emph{after} a routine open, to give them higher priority:
1330\begin{cfa}
1331void ?{}( S & s, int i ) with ( s ) `with( $\emph{\color{red}params}$ )` {
1332        s.i = i; j = 3; m = 5.5;
1333}
1334\end{cfa}
1335Finally, a cast may be used to disambiguate among overload variables in a @with@ expression:
1336\begin{cfa}
1337with ( w ) { ... }                                                      $\C{// ambiguous, same name and no context}$
1338with ( (S)w ) { ... }                                           $\C{// unambiguous, cast}$
1339\end{cfa}
1340and @with@ expressions may be complex expressions with type reference (see Section~\ref{s:References}) to aggregate:
1341\begin{cfa}
1342struct S { int i, j; } sv;
1343with ( sv ) {                                                           $\C{implicit reference}$
1344        S & sr = sv;
1345        with ( sr ) {                                                   $\C{explicit reference}$
1346                S * sp = &sv;
1347                with ( *sp ) {                                          $\C{computed reference}$
1348                        i = 3; j = 4;                                   $\C{\color{red}// sp-{\textgreater}i, sp-{\textgreater}j}$
1349                }
1350                i = 2; j = 3;                                           $\C{\color{red}// sr.i, sr.j}$
1351        }
1352        i = 1; j = 2;                                                   $\C{\color{red}// sv.i, sv.j}$
1353}
1354\end{cfa}
1355
1356
1357\subsection{Exception Handling}
1358
1359The following framework for \CFA exception handling is in place, excluding a run-time type information and dynamic casts.
1360\CFA provides two forms of exception handling: \newterm{fix-up} and \newterm{recovery} (see Figure~\ref{f:CFAExceptionHandling}).
1361Both 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.
1362\CFA restricts exception types to those defined by aggregate type @exception@.
1363The 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@).
1364If @resume@ or @throw@ have no exception type, it is a reresume/rethrow, meaning the currently exception continues propagation.
1365If there is no current exception, the reresume/rethrow results in a runtime error.
1366
1367\begin{figure}
1368\begin{cquote}
1369\lstDeleteShortInline@%
1370\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1371\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{Resumption}}       & \multicolumn{1}{c}{\textbf{Recovery}} \\
1372\begin{cfa}
1373`exception R { int fix; };`
1374void f() {
1375        R r;
1376        ... `resume( r );` ...
1377        ... r.fix // control does return here after handler
1378}
1379`try` {
1380        ... f(); ...
1381} `catchResume( R r )` {
1382        ... r.fix = ...; // return correction to raise
1383} // dynamic return to _Resume
1384\end{cfa}
1385&
1386\begin{cfa}
1387`exception T {};`
1388void f() {
1389
1390        ... `throw( T{} );` ...
1391        // control does NOT return here after handler
1392}
1393`try` {
1394        ... f(); ...
1395} `catch( T t )` {
1396        ... // recover and continue
1397} // static return to next statement
1398\end{cfa}
1399\end{tabular}
1400\lstMakeShortInline@%
1401\end{cquote}
1402\caption{\CFA Exception Handling}
1403\label{f:CFAExceptionHandling}
1404\end{figure}
1405
1406The set of exception types in a list of catch clause may include both a resumption and termination handler:
1407\begin{cfa}
1408try {
1409        ... resume( `R{}` ); ...
1410} catchResume( `R` r ) { ... throw( R{} ); ... } $\C{\color{red}// H1}$
1411   catch( `R` r ) { ... }                                       $\C{\color{red}// H2}$
1412
1413\end{cfa}
1414The resumption propagation raises @R@ and the stack is not unwound;
1415the exception is caught by the @catchResume@ clause and handler H1 is invoked.
1416The termination propagation in handler H1 raises @R@ and the stack is unwound;
1417the exception is caught by the @catch@ clause and handler H2 is invoked.
1418The termination handler is available because the resumption propagation did not unwind the stack.
1419
1420An additional feature is conditional matching in a catch clause:
1421\begin{cfa}
1422try {
1423        ... write( `datafile`, ... ); ...               $\C{// may throw IOError}$
1424        ... write( `logfile`, ... ); ...
1425} catch ( IOError err; `err.file == datafile` ) { ... } $\C{// handle datafile error}$
1426   catch ( IOError err; `err.file == logfile` ) { ... } $\C{// handle logfile error}$
1427   catch ( IOError err ) { ... }                        $\C{// handler error from other files}$
1428\end{cfa}
1429where the throw inserts the failing file-handle in the I/O exception.
1430Conditional catch cannot be trivially mimicked by other mechanisms because once an exception is caught, handler clauses in that @try@ statement are no longer eligible..
1431
1432The resumption raise can specify an alternate stack on which to raise an exception, called a \newterm{nonlocal raise}:
1433\begin{cfa}
1434resume( $\emph{exception-type}$, $\emph{alternate-stack}$ )
1435resume( $\emph{alternate-stack}$ )
1436\end{cfa}
1437These overloads of @resume@ raise the specified exception or the currently propagating exception (reresume) at another coroutine or task~\cite{Delisle18}.
1438Nonlocal raise is restricted to resumption to provide the exception handler the greatest flexibility because processing the exception does not unwind its stack, allowing it to continue after the handle returns.
1439
1440To facilitate nonlocal exception, \CFA provides dynamic enabling and disabling of nonlocal exception-propagation.
1441The constructs for controlling propagation of nonlocal exceptions are the @enable@ and the @disable@ blocks:
1442\begin{cquote}
1443\lstDeleteShortInline@%
1444\begin{tabular}{@{}l@{\hspace{2\parindentlnth}}l@{}}
1445\begin{cfa}
1446enable $\emph{exception-type-list}$ {
1447        // allow non-local resumption
1448}
1449\end{cfa}
1450&
1451\begin{cfa}
1452disable $\emph{exception-type-list}$ {
1453        // disallow non-local resumption
1454}
1455\end{cfa}
1456\end{tabular}
1457\lstMakeShortInline@%
1458\end{cquote}
1459The arguments for @enable@/@disable@ specify the exception types allowed to be propagated or postponed, respectively.
1460Specifying no exception type is shorthand for specifying all exception types.
1461Both @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.
1462
1463Finally, \CFA provides a Java like  @finally@ clause after the catch clauses:
1464\begin{cfa}
1465try {
1466        ... f(); ...
1467// catchResume or catch clauses
1468} `finally` {
1469        // house keeping
1470}
1471\end{cfa}
1472The finally clause is always executed, i.e., if the try block ends normally or if an exception is raised.
1473If an exception is raised and caught, the handler is run before the finally clause.
1474Like a destructor (see Section~\ref{s:ConstructorsDestructors}), a finally clause can raise an exception but not if there is an exception being propagated.
1475Mimicking the @finally@ clause with mechanisms like RAII is non-trivially when there are multiple types and local accesses.
1476
1477
1478\section{Declarations}
1479
1480Declarations in C have weaknesses and omissions.
1481\CFA attempts to correct and add to C declarations, while ensuring \CFA subjectively ``feels like'' C.
1482An 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.
1483Maintaining 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.
1484Nevertheless, some features from other approaches are undeniably convenient;
1485\CFA attempts to adapt these features to the C paradigm.
1486
1487
1488\subsection{Alternative Declaration Syntax}
1489
1490C declaration syntax is notoriously confusing and error prone.
1491For example, many C programmers are confused by a declaration as simple as:
1492\begin{cquote}
1493\lstDeleteShortInline@%
1494\begin{tabular}{@{}ll@{}}
1495\begin{cfa}
1496int * x[5]
1497\end{cfa}
1498&
1499\raisebox{-0.75\totalheight}{\input{Cdecl}}
1500\end{tabular}
1501\lstMakeShortInline@%
1502\end{cquote}
1503Is this an array of 5 pointers to integers or a pointer to an array of 5 integers?
1504If there is any doubt, it implies productivity and safety issues even for basic programs.
1505Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site.
1506For example, a routine returning a pointer to an array of integers is defined and used in the following way:
1507\begin{cfa}
1508int `(*`f`())[`5`]` {...};                                      $\C{// definition}$
1509 ... `(*`f`())[`3`]` += 1;                                      $\C{// usage}$
1510\end{cfa}
1511Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
1512While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice.
1513
1514\CFA provides its own type, variable and routine declarations, using a different syntax.
1515The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right.
1516The qualifiers have the same meaning but are ordered left to right to specify a variable's type.
1517\begin{cquote}
1518\lstDeleteShortInline@%
1519\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
1520\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1521\begin{cfa}
1522`[5] *` int x1;
1523`* [5]` int x2;
1524`[* [5] int]` f( int p );
1525\end{cfa}
1526&
1527\begin{cfa}
1528int `*` x1 `[5]`;
1529int `(*`x2`)[5]`;
1530`int (*`f( int p )`)[5]`;
1531\end{cfa}
1532&
1533\begin{cfa}
1534// array of 5 pointers to int
1535// pointer to an array of 5 int
1536// function returning pointer to an array of 5 int and taking an int
1537\end{cfa}
1538\end{tabular}
1539\lstMakeShortInline@%
1540\end{cquote}
1541The only exception is bit field specification, which always appear to the right of the base type.
1542% Specifically, the character @*@ is used to indicate a pointer, square brackets @[@\,@]@ are used to represent an array or function return value, and parentheses @()@ are used to indicate a routine parameter.
1543However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list.
1544For instance, variables @x@ and @y@ of type pointer to integer are defined in \CFA as follows:
1545\begin{cquote}
1546\lstDeleteShortInline@%
1547\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1548\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1549\begin{cfa}
1550`*` int x, y;
1551int y;
1552\end{cfa}
1553&
1554\begin{cfa}
1555int `*`x, `*`y;
1556
1557\end{cfa}
1558\end{tabular}
1559\lstMakeShortInline@%
1560\end{cquote}
1561The downside of the \CFA semantics is the need to separate regular and pointer declarations.
1562
1563\begin{comment}
1564Other examples are:
1565\begin{cquote}
1566\lstDeleteShortInline@%
1567\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
1568\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{C}}      \\
1569\begin{cfa}
1570[ 5 ] int z;
1571[ 5 ] * char w;
1572* [ 5 ] double v;
1573struct s {
1574        int f0:3;
1575        * int f1;
1576        [ 5 ] * int f2;
1577};
1578\end{cfa}
1579&
1580\begin{cfa}
1581int z[ 5 ];
1582char * w[ 5 ];
1583double (* v)[ 5 ];
1584struct s {
1585        int f0:3;
1586        int * f1;
1587        int * f2[ 5 ]
1588};
1589\end{cfa}
1590&
1591\begin{cfa}
1592// array of 5 integers
1593// array of 5 pointers to char
1594// pointer to array of 5 doubles
1595
1596// common bit field syntax
1597
1598
1599
1600\end{cfa}
1601\end{tabular}
1602\lstMakeShortInline@%
1603\end{cquote}
1604\end{comment}
1605
1606All 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:
1607\begin{cquote}
1608\lstDeleteShortInline@%
1609\begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}}
1610\multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\
1611\begin{cfa}
1612extern const * const int x;
1613static const * [ 5 ] const int y;
1614\end{cfa}
1615&
1616\begin{cfa}
1617int extern const * const x;
1618static const int (* const y)[ 5 ]
1619\end{cfa}
1620&
1621\begin{cfa}
1622// external const pointer to const int
1623// internal const pointer to array of 5 const int
1624\end{cfa}
1625\end{tabular}
1626\lstMakeShortInline@%
1627\end{cquote}
1628Specifiers must appear at the start of a \CFA routine declaration\footnote{\label{StorageClassSpecifier}
1629The 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}}.
1630
1631The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine @sizeof@:
1632\begin{cquote}
1633\lstDeleteShortInline@%
1634\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1635\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1636\begin{cfa}
1637y = (* int)x;
1638i = sizeof([ 5 ] * int);
1639\end{cfa}
1640&
1641\begin{cfa}
1642y = (int *)x;
1643i = sizeof(int * [ 5 ]);
1644\end{cfa}
1645\end{tabular}
1646\lstMakeShortInline@%
1647\end{cquote}
1648
1649The syntax of the new routine prototype declaration follows directly from the new routine definition syntax;
1650as well, parameter names are optional, \eg:
1651\begin{cfa}
1652[ int x ] f ( /* void */ );                                     $\C{// returning int with no parameters}$
1653[ int x ] f (...);                                                      $\C{// returning int with unknown parameters}$
1654[ * int ] g ( int y );                                          $\C{// returning pointer to int with int parameter}$
1655[ void ] h ( int, char );                                       $\C{// returning no result with int and char parameters}$
1656[ * int, int ] j ( int );                                       $\C{// returning pointer to int and int, with int parameter}$
1657\end{cfa}
1658This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
1659Like C, it is possible to declare multiple routine-prototypes in a single declaration, where the return type is distributed across \emph{all} routine names in the declaration list, \eg:
1660\begin{cquote}
1661\lstDeleteShortInline@%
1662\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
1663\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
1664\begin{cfa}
1665[double] foo(), foo( int ), foo( double ) {...}
1666\end{cfa}
1667&
1668\begin{cfa}
1669double foo1( void ), foo2( int ), foo3( double );
1670\end{cfa}
1671\end{tabular}
1672\lstMakeShortInline@%
1673\end{cquote}
1674where \CFA allows the last routine in the list to define its body.
1675
1676The syntax for pointers to \CFA routines specifies the pointer name on the right, \eg:
1677\begin{cfa}
1678* [ int x ] () fp;                                                      $\C{// pointer to routine returning int with no parameters}$
1679* [ * int ] ( int y ) gp;                                       $\C{// pointer to routine returning pointer to int with int parameter}$
1680* [ ] ( int, char ) hp;                                         $\C{// pointer to routine returning no result with int and char parameters}$
1681* [ * int, int ] ( int ) jp;                            $\C{// pointer to routine returning pointer to int and int, with int parameter}$
1682\end{cfa}
1683Note, a routine name cannot be specified:
1684\begin{cfa}
1685* [ int x ] f () fp;                                            $\C{// routine name "f" is disallowed}$
1686\end{cfa}
1687
1688Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration.
1689Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
1690Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX-like systems.
1691
1692
1693\subsection{References}
1694\label{s:References}
1695
1696All variables in C have an \newterm{address}, a \newterm{value}, and a \newterm{type};
1697at 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.
1698The C type-system does not always track the relationship between a value and its address;
1699a 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'').
1700For 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.
1701Despite 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.
1702
1703Within a lexical scope, lvalue expressions have an \newterm{address interpretation} for writing a value or a \newterm{value interpretation} to read a value.
1704For example, in @x = y@, @x@ has an address interpretation, while @y@ has a value interpretation.
1705While 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.
1706In C, for any type @T@ there is a pointer type @T *@, the value of which is the address of a value of type @T@.
1707A 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 @&?@.
1708
1709\begin{cfa}
1710int x = 1, y = 2, * p1, * p2, ** p3;
1711p1 = &x;                                                                        $\C{// p1 points to x}$
1712p2 = &y;                                                                        $\C{// p2 points to y}$
1713p3 = &p1;                                                                       $\C{// p3 points to p1}$
1714*p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15);
1715\end{cfa}
1716
1717Unfortunately, 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.
1718For 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.
1719However, 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.
1720To solve these problems, \CFA introduces reference types @T &@;
1721a @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:
1722
1723\begin{cfa}
1724int x = 1, y = 2, & r1, & r2, && r3;
1725&r1 = &x;                                                                       $\C{// r1 points to x}$
1726&r2 = &y;                                                                       $\C{// r2 points to y}$
1727&&r3 = &&r1;                                                            $\C{// r3 points to r2}$
1728r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15);       $\C{// implicit dereferencing}$
1729\end{cfa}
1730
1731Except for auto-dereferencing by the compiler, this reference example is exactly the same as the previous pointer example.
1732Hence, 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.
1733One 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:
1734
1735\begin{cfa}
1736`*`r2 = ((`*`r1 + `*`r2) * (`**`r3 - `*`r1)) / (`**`r3 - 15);
1737\end{cfa}
1738
1739References in \CFA are similar to those in \CC, with important improvements, which can be seen in the example above.
1740Firstly, \CFA does not forbid references to references.
1741This provides a much more orthogonal design for library implementors, obviating the need for workarounds such as @std::reference_wrapper@.
1742Secondly, \CFA references are rebindable, whereas \CC references have a fixed address.
1743\newsavebox{\LstBox}
1744\begin{lrbox}{\LstBox}
1745\lstset{basicstyle=\footnotesize\linespread{0.9}\sf}
1746\begin{cfa}
1747int & r = *new( int );
1748...                                                                                     $\C{// non-null reference}$
1749delete &r;
1750r += 1;                                                                         $\C{// undefined reference}$
1751\end{cfa}
1752\end{lrbox}
1753Rebinding allows \CFA references to be default-initialized (\eg to a null pointer\footnote{
1754While 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:
1755\begin{cquote}
1756\usebox{\LstBox}
1757\end{cquote}
1758}%
1759) and point to different addresses throughout their lifetime, like pointers.
1760Rebinding is accomplished by extending the existing syntax and semantics of the address-of operator in C.
1761
1762In 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.
1763In \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.
1764The 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.
1765This rebinding occurs to an arbitrary depth of reference nesting;
1766loosely speaking, nested address-of operators produce a nested lvalue pointer up to the depth of the reference.
1767These 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@.
1768More precisely:
1769\begin{itemize}
1770\item
1771if @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).
1772       
1773\item
1774if @L@ is an lvalue of type {@T &@$_1 \cdots$@ &@$_l$} where $l \ge 0$ references (@&@ symbols) then @&L@ has type {@T `*`&@$_{\color{red}1} \cdots$@ &@$_{\color{red}l}$}, \\ \ie @T@ pointer with $l$ references (@&@ symbols).
1775\end{itemize}
1776Since 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.
1777
1778By analogy to pointers, \CFA references also allow cv-qualifiers such as @const@:
1779\begin{cfa}
1780const int cx = 5;                                                       $\C{// cannot change cx}$
1781const int & cr = cx;                                            $\C{// cannot change cr's referred value}$
1782&cr = &cx;                                                                      $\C{// rebinding cr allowed}$
1783cr = 7;                                                                         $\C{// ERROR, cannot change cr}$
1784int & const rc = x;                                                     $\C{// must be initialized, like in \CC}$
1785&rc = &x;                                                                       $\C{// ERROR, cannot rebind rc}$
1786rc = 7;                                                                         $\C{// x now equal to 7}$
1787\end{cfa}
1788Given that a reference is meant to represent a lvalue, \CFA provides some syntactic shortcuts when initializing references.
1789There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, and return/temporary binding.
1790In each of these contexts, the address-of operator on the target lvalue is elided.
1791The 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@.
1792
1793More 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;
1794this conversion is used in any context in \CFA where an implicit conversion is allowed.
1795Similarly, 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.
1796The final reference conversion included in \CFA is ``rvalue-to-reference'' conversion, implemented by means of an implicit temporary.
1797When 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.
1798\begin{cfa}
1799struct S { double x, y; };
1800int i, j;
1801void f( int & i, int & j, S & s, int v[] );
1802f( 3, i + j, (S){ 1.0, 7.0 }, (int [3]){ 1, 2, 3 } );   $\C{// pass rvalue to lvalue \(\Rightarrow\) implicit temporary}$
1803\end{cfa}
1804This 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.
1805\CC allows a similar binding, but only for @const@ references; the more general semantics of \CFA are an attempt to avoid the \newterm{const hell} problem, in which addition of a @const@ qualifier to one reference requires a cascading chain of added qualifiers.
1806
1807
1808\subsection{Type Nesting}
1809
1810Nested types provide a mechanism to organize associated types and refactor a subset of fields into a named aggregate (\eg sub-aggregates @name@, @address@, @department@, within aggregate @employe@).
1811Java 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.
1812Since \CFA in not object-oriented, adopting dynamic scoping does not make sense;
1813instead \CFA adopts \CC static nesting, using the field-selection operator ``@.@'' for type qualification, as does Java, rather than the \CC type-selection operator ``@::@'' (see Figure~\ref{f:TypeNestingQualification}).
1814\begin{figure}
1815\centering
1816\lstDeleteShortInline@%
1817\begin{tabular}{@{}l@{\hspace{3em}}l|l@{}}
1818\multicolumn{1}{c@{\hspace{3em}}}{\textbf{C Type Nesting}}      & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}}      & \multicolumn{1}{|c}{\textbf{\CFA}}    \\
1819\hline
1820\begin{cfa}
1821struct S {
1822        enum C { R, G, B };
1823        struct T {
1824                union U { int i, j; };
1825                enum C c;
1826                short int i, j;
1827        };
1828        struct T t;
1829} s;
1830
1831int rtn() {
1832        s.t.c = R;
1833        struct T t = { R, 1, 2 };
1834        enum C c;
1835        union U u;
1836}
1837\end{cfa}
1838&
1839\begin{cfa}
1840enum C { R, G, B };
1841union U { int i, j; };
1842struct T {
1843        enum C c;
1844        short int i, j;
1845};
1846struct S {
1847        struct T t;
1848} s;
1849       
1850
1851
1852
1853
1854
1855
1856\end{cfa}
1857&
1858\begin{cfa}
1859struct S {
1860        enum C { R, G, B };
1861        struct T {
1862                union U { int i, j; };
1863                enum C c;
1864                short int i, j;
1865        };
1866        struct T t;
1867} s;
1868
1869int rtn() {
1870        s.t.c = `S.`R;  // type qualification
1871        struct `S.`T t = { `S.`R, 1, 2 };
1872        enum `S.`C c;
1873        union `S.T.`U u;
1874}
1875\end{cfa}
1876\end{tabular}
1877\lstMakeShortInline@%
1878\caption{Type Nesting / Qualification}
1879\label{f:TypeNestingQualification}
1880\end{figure}
1881In the C left example, types @C@, @U@ and @T@ are implicitly hoisted outside of type @S@ into the containing block scope.
1882In the \CFA right example, the types are not hoisted and accessible.
1883
1884
1885\subsection{Constructors and Destructors}
1886\label{s:ConstructorsDestructors}
1887
1888One 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.
1889However, this manual approach is often verbose, and it is useful to manage resources other than memory (\eg file handles) using the same mechanism as memory.
1890\CC addresses these issues using Resource Aquisition Is Initialization (RAII), implemented by means of \newterm{constructor} and \newterm{destructor} functions;
1891\CFA adopts constructors and destructors (and @finally@) to facilitate RAII.
1892While 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.
1893Specifically, \CFA constructors and destructors are denoted by name and first parameter-type versus name and nesting in an aggregate type.
1894Constructor 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.
1895
1896In \CFA, a constructor is named @?{}@ and a destructor is named @^?{}@.
1897The name @{}@ comes from the syntax for the initializer: @struct S { int i, j; } s = `{` 2, 3 `}`@\footnote{%
1898The symbol \lstinline+^+ is used for the destructor name because it was the last binary operator that could be used in a unary context.}.
1899Like other \CFA operators, these names represent the syntax used to call the constructor or destructor, \eg @?{}(x, ...)@ or @^{}(x, ...)@.
1900The constructor and destructor have return type @void@, and the first parameter is a reference to the object type to be constructed or destructed.
1901While the first parameter is informally called the @this@ parameter, as in object-oriented languages, any variable name may be used.
1902Both constructors and destructors allow additional parametes after the @this@ parameter for specifying values for initialization/de-initialization\footnote{
1903Destruction parameters are useful for specifying storage-management actions, such as de-initialize but not deallocate.}.
1904\begin{cfa}
1905struct VLA {
1906        int len, * data;
1907};
1908void ?{}( VLA & vla ) with ( vla ) {            $\C{// default constructor}$
1909        len = 10;  data = alloc( len );                 $\C{// shallow copy}$
1910}
1911void ^?{}( VLA & vla ) with ( vla ) {           $\C{// destructor}$
1912        free( data );
1913}
1914{
1915        VLA x;                                                                  $\C{// implicit:  ?\{\}( x );}$
1916}                                                                                       $\C{// implicit:  ?\^{}\{\}( x );}$
1917\end{cfa}
1918(Note, the example is purposely kept simple by using shallow-copy semantics.)
1919@VLA@ is a \newterm{managed type}\footnote{
1920A managed type affects the runtime environment versus a self-contained type.}: a type requiring a non-trivial constructor or destructor, or with a field of a managed type.
1921A 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.
1922For details of the code-generation placement of implicit constructor and destructor calls among complex executable statements see~\cite[\S~2.2]{Schluntz17}.
1923
1924\CFA also provides syntax for \newterm{initialization} and \newterm{copy}:
1925\begin{cfa}
1926void ?{}( VLA & vla, int size, char fill ) with ( vla ) {       $\C{// initialization}$
1927        len = size;  data = alloc( len, fill );
1928}
1929void ?{}( VLA & vla, VLA other ) {                      $\C{// copy}$
1930        vla.len = other.len;  vla.data = other.data;
1931}
1932\end{cfa}
1933An 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).
1934\begin{cfa}
1935VLA va = `{` 20, 0 `}`,  * arr = alloc()`{` 5, 0 `}`;
1936\end{cfa}
1937Note, the use of a \newterm{constructor expression} to initialize the storage from the dynamic storage-allocation.
1938Like \CC, the copy constructor has two parameters, the second of which is a value parameter with the same type as the first parameter;
1939appropriate care is taken to not recursively call the copy constructor when initializing the second parameter.
1940
1941\CFA constructors may be explicitly call, like Java, and destructors may be explicitly called, like \CC.
1942Explicit calls to constructors double as a \CC-style \emph{placement syntax}, useful for construction of member fields in user-defined constructors and reuse of existing storage allocations.
1943While existing call syntax works for explicit calls to constructors and destructors, \CFA also provides a more concise \newterm{operator syntax} for both:
1944\begin{cfa}
1945{
1946        VLA x,  y = { 20, 0x01 },  z = y;
1947        // implicit:  ?{}( x );  ?{}( y, 20, 0x01 );  ?{}( z, y ); z points to y
1948        ^x{};                                                                   $\C{// deallocate x}$
1949        x{};                                                                    $\C{// reallocate x}$
1950        z{ 5, 0xff };                                                   $\C{// reallocate z, not pointing to y}$
1951        ^y{};                                                                   $\C{// deallocate y}$
1952        y{ x };                                                                 $\C{// reallocate y, points to x}$
1953        x{};                                                                    $\C{// reallocate x, not pointing to y}$
1954        // implicit:  ^?{}(z);  ^?{}(y);  ^?{}(x);
1955}
1956\end{cfa}
1957
1958To 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.
1959These default functions can be overridden by user-generated versions.
1960For 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;
1961if default zero-initialization is desired, the default constructors can be overridden.
1962For user-generated types, the four functions are also automatically generated.
1963@enum@ types are handled the same as their underlying integral type, and unions are also bitwise copied and no-op initialized and destructed.
1964For compatibility with C, a copy constructor from the first union member type is also defined.
1965For @struct@ types, each of the four functions are implicitly defined to call their corresponding functions on each member of the struct.
1966To better simulate the behaviour of C initializers, a set of \newterm{field constructors} is also generated for structures.
1967A 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.
1968To 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 field constructors for that type are hidden from expression resolution;
1969similarly, the generated default constructor is hidden upon declaration of any constructor.
1970These semantics closely mirror the rule for implicit declaration of constructors in \CC\cite[p.~186]{ANSI98:C++}.
1971
1972In some circumstance programmers may not wish to have constructor and destructor calls.
1973In these cases, \CFA provides the initialization syntax \lstinline|S x @= {}|, and the object becomes unmanaged, so implicit constructor and destructor calls are not generated.
1974Any C initializer can be the right-hand side of an \lstinline|@=| initializer, \eg \lstinline|VLA a @= { 0, 0x0 }|, with the usual C initialization semantics.
1975The 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.
1976
1977
1978% \subsection{Default Parameters}
1979
1980
1981\section{Literals}
1982
1983C 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.
1984In 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.
1985A trivial example is allowing the underscore to separate prefixes, digits, and suffixes in all \CFA constants, as in Ada, \eg @0x`_`1.ffff`_`ffff`_`p`_`128`_`l@.
1986
1987
1988\subsection{0/1}
1989
1990In C, @0@ has the special property that it is the only ``false'' value; by the standard, any value which compares equal to @0@ is false, while any value that compares unequal to @0@ is true.
1991As 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.
1992The operator overloading feature of \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.
1993To provide this precision, \CFA introduces a new type @zero_t@ as type type of literal @0@ (somewhat analagous to @nullptr_t@ and @nullptr@ in \CCeleven); @zero_t@ can only take the value @0@, but has implicit conversions to the integer and pointer types so that C code involving @0@ continues to work properly.
1994With this addition, the \CFA compiler rewrites @if (x)@ and similar expressions to @if ((x) != 0)@ or the appropriate analogue, and any type @T@ can be made ``truthy'' by defining an operator overload @int ?!=?(T, zero_t)@.
1995\CC makes types truthy by adding a conversion to @bool@; prior to the addition of explicit cast operators in \CCeleven this approach had the pitfall of making truthy types transitively convertable to any numeric type; our design for \CFA avoids this issue.
1996
1997\CFA also includes a special type for @1@, @one_t@; like @zero_t@, @one_t@ has built-in implicit conversions to the various integral types so that @1@ maintains its expected semantics in legacy code.
1998The addition of @one_t@ allows generic algorithms to handle the unit value uniformly for types where that is meaningful.
1999\TODO{Make this sentence true} In particular, polymorphic functions in the \CFA prelude define @++x@ and @x++@ in terms of @x += 1@, allowing users to idiomatically define all forms of increment for a type @T@ by defining the single function @T & ?+=(T &, one_t)@; analogous overloads for the decrement operators are present as well.
2000
2001
2002\subsection{Integral Suffixes}
2003
2004Additional integral suffixes are added to cover all the integral types and lengths.
2005\begin{cquote}
2006\lstDeleteShortInline@%
2007\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
2008\begin{cfa}
200920_hh     // signed char
201021_hhu   // unsigned char
201122_h      // signed short int
201223_uh    // unsigned short int
201324z        // size_t
2014\end{cfa}
2015&
2016\begin{cfa}
201720_L8     // int8_t
201821_ul8    // uint8_t
201922_l16    // int16_t
202023_ul16  // uint16_t
202124_l32    // int32_t
2022\end{cfa}
2023&
2024\begin{cfa}
202525_ul32      // uint32_t
202626_l64        // int64_t
202727_l64u      // uint64_t
202826_L128     // int128
202927_L128// unsigned int128
2030\end{cfa}
2031\end{tabular}
2032\lstMakeShortInline@%
2033\end{cquote}
2034
2035
2036\subsection{Units}
2037
2038Alternative call syntax (literal argument before routine name) to convert basic literals into user literals.
2039
2040{\lstset{language=CFA,moredelim=**[is][\color{red}]{|}{|},deletedelim=**[is][]{`}{`}}
2041\begin{cfa}
2042struct Weight { double stones; };
2043void ?{}( Weight & w ) { w.stones = 0; }        $\C{// operations}$
2044void ?{}( Weight & w, double w ) { w.stones = w; }
2045Weight ?+?( Weight l, Weight r ) { return (Weight){ l.stones + r.stones }; }
2046
2047Weight |?`st|( double w ) { return (Weight){ w }; } $\C{// backquote for units}$
2048Weight |?`lb|( double w ) { return (Weight){ w / 14.0 }; }
2049Weight |?`kg|( double w ) { return (Weight) { w * 0.1575}; }
2050
2051int main() {
2052        Weight w, heavy = { 20 };                               $\C{// 20 stone}$
2053        w = 155|`lb|;
2054        w = 0x_9b_u|`lb|;                                               $\C{// hexadecimal unsigned weight (155)}$
2055        w = 0_233|`lb|;                                                 $\C{// octal weight (155)}$
2056        w = 5|`st| + 8|`kg| + 25|`lb| + heavy;
2057}
2058\end{cfa}
2059}%
2060
2061
2062\section{Libraries}
2063\label{sec:libraries}
2064
2065As 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.
2066\CFA has replacement libraries condensing hundreds of existing C names into tens of \CFA overloaded names, all without rewriting the actual computations.
2067In many cases, the interface is an inline wrapper providing overloading during compilation but zero cost at runtime.
2068The following sections give a glimpse of the interface reduction to many C libraries.
2069In many cases, @signed@/@unsigned@ @char@ and @short@ routines are available (but not shown) to ensure expression computations remain in a single type, as conversions can distort results.
2070
2071
2072\subsection{Limits}
2073
2074C library @limits.h@ provides lower and upper bound constants for the basic types.
2075\CFA name overloading is used to condense these typed constants, \eg:
2076\begin{cquote}
2077\lstDeleteShortInline@%
2078\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2079\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{Definition}}       & \multicolumn{1}{c}{\textbf{Usage}}    \\
2080\begin{cfa}
2081const short int `MIN` = -32768;
2082const int `MIN` = -2147483648;
2083const long int `MIN` = -9223372036854775808L;
2084\end{cfa}
2085&
2086\begin{cfa}
2087short int si = `MIN`;
2088int i = `MIN`;
2089long int li = `MIN`;
2090\end{cfa}
2091\end{tabular}
2092\lstMakeShortInline@%
2093\end{cquote}
2094The result is a significant reduction in names to access typed constants, \eg:
2095\begin{cquote}
2096\lstDeleteShortInline@%
2097\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2098\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
2099\begin{cfa}
2100MIN
2101MAX
2102M_PI
2103M_E
2104\end{cfa}
2105&
2106\begin{cfa}
2107SCHAR_MIN, CHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN, LLONG_MIN,
2108SCHAR_MAX, UCHAR_MAX, SHRT_MAX, INT_MAX, LONG_MAX, LLONG_MAX,
2109M_PI, M_PIl, M_CPI, M_CPIl,
2110M_E, M_El, M_CE, M_CEl
2111\end{cfa}
2112\end{tabular}
2113\lstMakeShortInline@%
2114\end{cquote}
2115
2116
2117\subsection{Math}
2118
2119C library @math.h@ provides many mathematical routines.
2120\CFA routine overloading is used to condense these mathematical routines, \eg:
2121\begin{cquote}
2122\lstDeleteShortInline@%
2123\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2124\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{Definition}}       & \multicolumn{1}{c}{\textbf{Usage}}    \\
2125\begin{cfa}
2126float `log`( float x );
2127double `log`( double );
2128double _Complex `log`( double _Complex x );
2129\end{cfa}
2130&
2131\begin{cfa}
2132float f = `log`( 3.5 );
2133double d = `log`( 3.5 );
2134double _Complex dc = `log`( 3.5+0.5I );
2135\end{cfa}
2136\end{tabular}
2137\lstMakeShortInline@%
2138\end{cquote}
2139The result is a significant reduction in names to access math routines, \eg:
2140\begin{cquote}
2141\lstDeleteShortInline@%
2142\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2143\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
2144\begin{cfa}
2145log
2146sqrt
2147sin
2148\end{cfa}
2149&
2150\begin{cfa}
2151logf, log, logl, clogf, clog, clogl
2152sqrtf, sqrt, sqrtl, csqrtf, csqrt, csqrtl
2153sinf, sin, sinl, csinf, csin, csinl
2154\end{cfa}
2155\end{tabular}
2156\lstMakeShortInline@%
2157\end{cquote}
2158While \Celeven has type-generic math~\cite[\S~7.25]{C11} in @tgmath.h@ to provide a similar mechanism, these macros are limited, matching a routine name with a single set of floating type(s).
2159For example, it is impossible to overload @atan@ for both one and two arguments;
2160instead the names @atan@ and @atan2@ are required.
2161The key observation is that only a restricted set of type-generic macros are provided for a limited set of routine names, which do not generalize across the type system, as in \CFA.
2162
2163
2164\subsection{Standard}
2165
2166C library @stdlib.h@ provides many general routines.
2167\CFA routine overloading is used to condense these utility routines, \eg:
2168\begin{cquote}
2169\lstDeleteShortInline@%
2170\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2171\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{Definition}}       & \multicolumn{1}{c}{\textbf{Usage}}    \\
2172\begin{cfa}
2173unsigned int `abs`( int );
2174double `abs`( double );
2175double abs( double _Complex );
2176\end{cfa}
2177&
2178\begin{cfa}
2179unsigned int i = `abs`( -1 );
2180double d = `abs`( -1.5 );
2181double d = `abs`( -1.5+0.5I );
2182\end{cfa}
2183\end{tabular}
2184\lstMakeShortInline@%
2185\end{cquote}
2186The result is a significant reduction in names to access utility routines, \eg:
2187\begin{cquote}
2188\lstDeleteShortInline@%
2189\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2190\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
2191\begin{cfa}
2192abs
2193strto
2194random
2195\end{cfa}
2196&
2197\begin{cfa}
2198abs, labs, llabs, fabsf, fabs, fabsl, cabsf, cabs, cabsl
2199strtol, strtoul, strtoll, strtoull, strtof, strtod, strtold
2200srand48, mrand48, lrand48, drand48
2201\end{cfa}
2202\end{tabular}
2203\lstMakeShortInline@%
2204\end{cquote}
2205In additon, there are polymorphic routines, like @min@ and @max@, which work on any type with operators @?<?@ or @?>?@.
2206
2207The following shows one example where \CFA \emph{extends} an existing standard C interface to reduce complexity and provide safety.
2208C/\Celeven provide a number of complex and overlapping storage-management operation to support the following capabilities:
2209\begin{description}[topsep=3pt,itemsep=2pt,parsep=0pt]
2210\item[fill]
2211after allocation the storage is filled with a specified character.
2212\item[resize]
2213an existing allocation is decreased or increased in size.
2214In 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.
2215For an increase in storage size, new storage after the copied data may be filled.
2216\item[alignment]
2217an allocation starts on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes.
2218\item[array]
2219the allocation size is scaled to the specified number of array elements.
2220An array may be filled, resized, or aligned.
2221\end{description}
2222Table~\ref{t:StorageManagementOperations} shows the capabilities provided by C/\Celeven allocation-routines and how all the capabilities can be combined into two \CFA routines.
2223
2224\CFA storage-management routines extend the C equivalents by overloading, providing shallow type-safety, and removing the need to specify the base allocation-size.
2225The following example contrasts \CFA and C storage-allocation operation performing the same operations with the same type safety:
2226\begin{cquote}
2227\begin{cfa}[aboveskip=0pt]
2228size_t  dim = 10;                                                       $\C{// array dimension}$
2229char fill = '\xff';                                                     $\C{// initialization fill value}$
2230int * ip;
2231\end{cfa}
2232\lstDeleteShortInline@%
2233\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2234\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{C}}        \\
2235\begin{cfa}
2236ip = alloc();
2237ip = alloc( fill );
2238ip = alloc( dim );
2239ip = alloc( dim, fill );
2240ip = alloc( ip, 2 * dim );
2241ip = alloc( ip, 4 * dim, fill );
2242
2243ip = align_alloc( 16 );
2244ip = align_alloc( 16, fill );
2245ip = align_alloc( 16, dim );
2246ip = align_alloc( 16, dim, fill );
2247\end{cfa}
2248&
2249\begin{cfa}
2250ip = (int *)malloc( sizeof( int ) );
2251ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, sizeof( int ) );
2252ip = (int *)malloc( dim * sizeof( int ) );
2253ip = (int *)malloc( sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
2254ip = (int *)realloc( ip, 2 * dim * sizeof( int ) );
2255ip = (int *)realloc( ip, 4 * dim * sizeof( int ) ); memset( ip, fill, 4 * dim * sizeof( int ) );
2256
2257ip = memalign( 16, sizeof( int ) );
2258ip = memalign( 16, sizeof( int ) ); memset( ip, fill, sizeof( int ) );
2259ip = memalign( 16, dim * sizeof( int ) );
2260ip = memalign( 16, dim * sizeof( int ) ); memset( ip, fill, dim * sizeof( int ) );
2261\end{cfa}
2262\end{tabular}
2263\lstMakeShortInline@%
2264\end{cquote}
2265Variadic @new@ (see Section~\ref{sec:variadic-tuples}) cannot support the same overloading because extra parameters are for initialization.
2266Hence, there are @new@ and @anew@ routines for single and array variables, and the fill value is the arguments to the constructor, \eg:
2267\begin{cfa}
2268struct S { int i, j; };
2269void ?{}( S & s, int i, int j ) { s.i = i; s.j = j; }
2270S * s = new( 2, 3 );                                            $\C{// allocate storage and run constructor}$
2271S * as = anew( dim, 2, 3 );                                     $\C{// each array element initialized to 2, 3}$
2272\end{cfa}
2273Note, \CC can only initialization array elements via the default constructor.
2274
2275Finally, the \CFA memory-allocator has \newterm{sticky properties} for dynamic storage: fill and alignment are remembered with an object's storage in the heap.
2276When a @realloc@ is performed, the sticky properties are respected, so that new storage is correctly aligned and initialized with the fill character.
2277
2278\begin{table}
2279\centering
2280\lstDeleteShortInline@%
2281\lstMakeShortInline~%
2282\begin{tabular}{@{}r|r|l|l|l|l@{}}
2283\multicolumn{1}{c}{}&           & \multicolumn{1}{c|}{fill}     & resize        & alignment     & array \\
2284\hline
2285C               & ~malloc~                      & no                    & no            & no            & no    \\
2286                & ~calloc~                      & yes (0 only)  & no            & no            & yes   \\
2287                & ~realloc~                     & no/copy               & yes           & no            & no    \\
2288                & ~memalign~            & no                    & no            & yes           & no    \\
2289                & ~posix_memalign~      & no                    & no            & yes           & no    \\
2290\hline
2291C11             & ~aligned_alloc~       & no                    & no            & yes           & no    \\
2292\hline
2293\CFA    & ~alloc~                       & yes/copy              & no/yes        & no            & yes   \\
2294                & ~align_alloc~         & yes                   & no            & yes           & yes   \\
2295\end{tabular}
2296\lstDeleteShortInline~%
2297\lstMakeShortInline@%
2298\caption{Storage-Management Operations}
2299\label{t:StorageManagementOperations}
2300\end{table}
2301
2302
2303\subsection{I/O}
2304\label{s:IOLibrary}
2305
2306The goal of \CFA I/O is to simplify the common cases, while fully supporting polymorphism and user defined types in a consistent way.
2307The approach combines ideas from \CC and Python.
2308The \CFA header file for the I/O library is @fstream@.
2309
2310The common case is printing out a sequence of variables separated by whitespace.
2311\begin{cquote}
2312\lstDeleteShortInline@%
2313\begin{tabular}{@{}l@{\hspace{\parindentlnth}}l@{}}
2314\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{c}{\textbf{\CC}}      \\
2315\begin{cfa}
2316int x = 1, y = 2, z = 3;
2317sout | x `|` y `|` z | endl;
2318\end{cfa}
2319&
2320\begin{cfa}
2321
2322cout << x `<< " "` << y `<< " "` << z << endl;
2323\end{cfa}
2324\\
2325\begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt]
23261` `2` `3
2327\end{cfa}
2328&
2329\begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt]
23301 2 3
2331\end{cfa}
2332\end{tabular}
2333\lstMakeShortInline@%
2334\end{cquote}
2335The \CFA form has half the characters of the \CC form, and is similar to Python I/O with respect to implicit separators.
2336Similar simplification occurs for tuple I/O, which prints all tuple values separated by ``\lstinline[showspaces=true]@, @''.
2337\begin{cfa}
2338[int, [ int, int ] ] t1 = [ 1, [ 2, 3 ] ], t2 = [ 4, [ 5, 6 ] ];
2339sout | t1 | t2 | endl;                                  $\C{// print tuples}$
2340\end{cfa}
2341\begin{cfa}[showspaces=true,aboveskip=0pt]
23421`, `2`, `3 4`, `5`, `6
2343\end{cfa}
2344Finally, \CFA uses the logical-or operator for I/O as it is the lowest-priority overloadable operator, other than assignment.
2345Therefore, fewer output expressions require parenthesis.
2346\begin{cquote}
2347\lstDeleteShortInline@%
2348\begin{tabular}{@{}ll@{}}
2349\textbf{\CFA:}
2350&
2351\begin{cfa}
2352sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
2353\end{cfa}
2354\\
2355\textbf{\CC:}
2356&
2357\begin{cfa}
2358cout << x * 3 << y + 1 << `(`z << 2`)` << `(`x == y`)` << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
2359\end{cfa}
2360\\
2361\textbf{output:}
2362&
2363\begin{cfa}[showspaces=true,aboveskip=0pt]
23643 3 12 0 3 1 2
2365\end{cfa}
2366\end{tabular}
2367\lstMakeShortInline@%
2368\end{cquote}
2369There 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.
2370
2371The implicit separator character (space/blank) is a separator not a terminator.
2372The rules for implicitly adding the separator are:
2373\begin{itemize}
2374\item
2375A separator does not appear at the start or end of a line.
2376\item
2377A separator does not appear before or after a character literal or variable.
2378\item
2379A separator does not appear before or after a null (empty) C string, which is a local mechanism to disable insertion of the separator character.
2380\item
2381A separator does not appear before a C string starting with the characters: \lstinline[mathescape=off,basicstyle=\tt]@([{=$@
2382\item
2383A separator does not appear after a C string ending with the characters: \lstinline[basicstyle=\tt]@,.;!?)]}%@
2384\item
2385{\lstset{language=CFA,deletedelim=**[is][]{`}{`}}
2386A separator does not appear before or after a C string beginning/ending with the quote or whitespace characters: \lstinline[basicstyle=\tt,showspaces=true]@`'": \t\v\f\r\n@
2387}%
2388\end{itemize}
2389There are routines to set and get the separator string, and manipulators to toggle separation on and off in the middle of output.
2390
2391
2392\subsection{Multi-precision Integers}
2393\label{s:MultiPrecisionIntegers}
2394
2395\CFA has an interface to the GMP multi-precision signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP.
2396The \CFA interface wraps GMP routines into operator routines to make programming with multi-precision integers identical to using fixed-sized integers.
2397The \CFA type name for multi-precision signed-integers is @Int@ and the header file is @gmp@.
2398The following multi-precision factorial programs contrast using GMP with the \CFA and C interfaces.
2399\begin{cquote}
2400\lstDeleteShortInline@%
2401\begin{tabular}{@{}l@{\hspace{\parindentlnth}}@{\hspace{\parindentlnth}}l@{}}
2402\multicolumn{1}{c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}     & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
2403\begin{cfa}
2404#include <gmp>
2405int main( void ) {
2406        sout | "Factorial Numbers" | endl;
2407        Int fact = 1;
2408        sout | 0 | fact | endl;
2409        for ( unsigned int i = 1; i <= 40; i += 1 ) {
2410                fact *= i;
2411                sout | i | fact | endl;
2412        }
2413}
2414\end{cfa}
2415&
2416\begin{cfa}
2417#include <gmp.h>
2418int main( void ) {
2419        `gmp_printf`( "Factorial Numbers\n" );
2420        `mpz_t` fact;  `mpz_init_set_ui`( fact, 1 );
2421        `gmp_printf`( "%d %Zd\n", 0, fact );
2422        for ( unsigned int i = 1; i <= 40; i += 1 ) {
2423                `mpz_mul_ui`( fact, fact, i );
2424                `gmp_printf`( "%d %Zd\n", i, fact );
2425        }
2426}
2427\end{cfa}
2428\end{tabular}
2429\lstMakeShortInline@%
2430\end{cquote}
2431
2432
2433\section{Evaluation}
2434\label{sec:eval}
2435
2436Though \CFA provides significant added functionality over C, these features have a low runtime penalty.
2437In fact, \CFA's features for generic programming can enable faster runtime execution than idiomatic @void *@-based C code.
2438This claim is demonstrated through a set of generic-code-based micro-benchmarks in C, \CFA, and \CC (see stack implementations in Appendix~\ref{sec:BenchmarkStackImplementation}).
2439Since all these languages share a subset essentially comprising standard C, maximal-performance benchmarks would show little runtime variance, other than in length and clarity of source code.
2440A more illustrative benchmark measures the costs of idiomatic usage of each language's features.
2441Figure~\ref{fig:BenchmarkTest} shows the \CFA benchmark tests for a generic stack based on a singly linked-list, a generic pair-data-structure, and a variadic @print@ routine similar to that in Section~\ref{sec:variadic-tuples}.
2442The benchmark test is similar for C and \CC.
2443The experiment uses element types @int@ and @pair(_Bool, char)@, and pushes $N=40M$ elements on a generic stack, copies the stack, clears one of the stacks, finds the maximum value in the other stack, and prints $N/2$ (to reduce graph height) constants.
2444
2445\begin{figure}
2446\begin{cfa}[xleftmargin=3\parindentlnth,aboveskip=0pt,belowskip=0pt]
2447int main( int argc, char * argv[] ) {
2448        FILE * out = fopen( "cfa-out.txt", "w" );
2449        int maxi = 0, vali = 42;
2450        stack(int) si, ti;
2451
2452        REPEAT_TIMED( "push_int", N, push( &si, vali ); )
2453        TIMED( "copy_int", ti = si; )
2454        TIMED( "clear_int", clear( &si ); )
2455        REPEAT_TIMED( "pop_int", N,
2456                int xi = pop( &ti ); if ( xi > maxi ) { maxi = xi; } )
2457        REPEAT_TIMED( "print_int", N/2, print( out, vali, ":", vali, "\n" ); )
2458
2459        pair(_Bool, char) maxp = { (_Bool)0, '\0' }, valp = { (_Bool)1, 'a' };
2460        stack(pair(_Bool, char)) sp, tp;
2461
2462        REPEAT_TIMED( "push_pair", N, push( &sp, valp ); )
2463        TIMED( "copy_pair", tp = sp; )
2464        TIMED( "clear_pair", clear( &sp ); )
2465        REPEAT_TIMED( "pop_pair", N,
2466                pair(_Bool, char) xp = pop( &tp ); if ( xp > maxp ) { maxp = xp; } )
2467        REPEAT_TIMED( "print_pair", N/2, print( out, valp, ":", valp, "\n" ); )
2468        fclose(out);
2469}
2470\end{cfa}
2471\caption{\protect\CFA Benchmark Test}
2472\label{fig:BenchmarkTest}
2473\end{figure}
2474
2475The structure of each benchmark implemented is: C with @void *@-based polymorphism, \CFA with the presented features, \CC with templates, and \CC using only class inheritance for polymorphism, called \CCV.
2476The \CCV variant illustrates an alternative object-oriented idiom where all objects inherit from a base @object@ class, mimicking a Java-like interface;
2477hence runtime checks are necessary to safely down-cast objects.
2478The 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.
2479For the print benchmark, idiomatic printing is used: the C and \CFA variants used @stdio.h@, while the \CC and \CCV variants used @iostream@; preliminary tests show this distinction has negligible runtime impact.
2480Note, the C benchmark uses unchecked casts as there is no runtime mechanism to perform such checks, while \CFA and \CC provide type-safety statically.
2481
2482Figure~\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.
2483The graph plots the median of 5 consecutive runs of each program, with an initial warm-up run omitted.
2484All code is compiled at \texttt{-O2} by gcc or g++ 6.2.0, with all \CC code compiled as \CCfourteen.
2485The 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.
2486
2487\begin{figure}
2488\centering
2489\input{timing}
2490\caption{Benchmark Timing Results (smaller is better)}
2491\label{fig:eval}
2492\end{figure}
2493
2494\begin{table}
2495\centering
2496\caption{Properties of benchmark code}
2497\label{tab:eval}
2498\newcommand{\CT}[1]{\multicolumn{1}{c}{#1}}
2499\begin{tabular}{rrrrr}
2500                                                                        & \CT{C}        & \CT{\CFA}     & \CT{\CC}      & \CT{\CCV}             \\ \hline
2501maximum memory usage (MB)                       & 10001         & 2502          & 2503          & 11253                 \\
2502source code size (lines)                        & 247           & 222           & 165           & 339                   \\
2503redundant type annotations (lines)      & 39            & 2                     & 2                     & 15                    \\
2504binary size (KB)                                        & 14            & 229           & 18            & 38                    \\
2505\end{tabular}
2506\end{table}
2507
2508The 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;
2509this inefficiency is exacerbated by the second level of generic types in the pair-based benchmarks.
2510By contrast, the \CFA and \CC variants run in roughly equivalent time for both the integer and pair of @_Bool@ and @char@ because the storage layout is equivalent, with the inlined libraries (\ie no separate compilation) and greater maturity of the \CC compiler contributing to its lead.
2511\CCV is slower than C largely due to the cost of runtime type-checking of down-casts (implemented with @dynamic_cast@);
2512There are two outliers in the graph for \CFA: all prints and pop of @pair@.
2513Both of these cases result from the complexity of the C-generated polymorphic code, so that the gcc compiler is unable to optimize some dead code and condense nested calls.
2514A compiler designed for \CFA could easily perform these optimizations.
2515Finally, the binary size for \CFA is larger because of static linking with the \CFA libraries.
2516
2517\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 73 and 54 lines, respectively.
2518On 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.
2519\CCV does not use the \CC standard template library by construction, and in fact includes the definition of @object@ and wrapper classes for @bool@, @char@, @int@, and @const char *@ in its line count, which inflates this count somewhat, as an actual object-oriented language would include these in the standard library;
2520with their omission, the \CCV line count is similar to C.
2521We 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.
2522
2523Raw line-count, however, is a fairly rough measure of code complexity;
2524another important factor is how much type information the programmer must manually specify, especially where that information is not checked by the compiler.
2525Such 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 pointers arguments and format codes, or \CCV, with its extensive use of un-type-checked downcasts (\eg @object@ to @integer@ when popping a stack, or @object@ to @printable@ when printing the elements of a @pair@).
2526To quantify this, the ``redundant type annotations'' line in Table~\ref{tab:eval} counts the number of lines on which the type of a known variable is re-specified, either as a format specifier, explicit downcast, type-specific function, or by name in a @sizeof@, struct literal, or @new@ expression.
2527The \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.
2528The two instances in which the \CFA benchmark still uses redundant type specifiers are to cast the result of a polymorphic @malloc@ call (the @sizeof@ argument is inferred by the compiler).
2529These uses are similar to the @new@ expressions in \CC, though the \CFA compiler's type resolver should shortly render even these type casts superfluous.
2530
2531
2532\section{Related Work}
2533
2534
2535\subsection{Polymorphism}
2536
2537\CC is the most similar language to \CFA;
2538both are extensions to C with source and runtime backwards compatibility.
2539The fundamental difference is in their engineering approach to C compatibility and programmer expectation.
2540While \CC provides good backwards compatibility with C, it has a steep learning curve for many of its extensions.
2541For example, polymorphism is provided via three disjoint mechanisms: overloading, inheritance, and templates.
2542The 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.
2543In 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.
2544The key mechanism to support separate compilation is \CFA's \emph{explicit} use of assumed properties for a type.
2545Until \CC concepts~\cite{C++Concepts} are standardized (anticipated for \CCtwenty), \CC provides no way to specify the requirements of a generic function in code beyond compilation errors during template expansion;
2546furthermore, \CC concepts are restricted to template polymorphism.
2547
2548Cyclone~\cite{Grossman06} also provides capabilities for polymorphic functions and existential types, similar to \CFA's @forall@ functions and generic types.
2549Cyclone 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.
2550Furthermore, 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@.
2551In \CFA terms, all Cyclone polymorphism must be dtype-static.
2552While 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.
2553Smith 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.
2554
2555Objective-C~\cite{obj-c-book} is an industrially successful extension to C.
2556However, Objective-C is a radical departure from C, using an object-oriented model with message-passing.
2557Objective-C did not support type-checked generics until recently \cite{xcode7}, historically using less-efficient runtime checking of object types.
2558The GObject~\cite{GObject} framework also adds object-oriented programming with runtime type-checking and reference-counting garbage-collection to C;
2559these features are more intrusive additions than those provided by \CFA, in addition to the runtime overhead of reference-counting.
2560Vala~\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.
2561Java~\cite{Java8} included generic types in Java~5, which are type-checked at compilation and type-erased at runtime, similar to \CFA's.
2562However, in Java, each object carries its own table of method pointers, while \CFA passes the method pointers separately to maintain a C-compatible layout.
2563Java is also a garbage-collected, object-oriented language, with the associated resource usage and C-interoperability burdens.
2564
2565D~\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.
2566However, 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.
2567D and Go are garbage-collected languages, imposing the associated runtime overhead.
2568The necessity of accounting for data transfer between managed runtimes and the unmanaged C runtime complicates foreign-function interfaces to C.
2569Furthermore, 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.
2570D 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.
2571Rust also possesses much more powerful abstraction capabilities for writing generic code than Go.
2572On 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.
2573\CFA, with its more modest safety features, allows direct ports of C code while maintaining the idiomatic style of the original source.
2574
2575
2576\subsection{Tuples/Variadics}
2577
2578Many programming languages have some form of tuple construct and/or variadic functions, \eg SETL, C, KW-C, \CC, D, Go, Java, ML, and Scala.
2579SETL~\cite{SETL} is a high-level mathematical programming language, with tuples being one of the primary data types.
2580Tuples in SETL allow subscripting, dynamic expansion, and multiple assignment.
2581C 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.
2582KW-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.
2583The main contributions of that work were adding MRVF, tuple mass and multiple assignment, and record-field access.
2584\CCeleven introduced @std::tuple@ as a library variadic template structure.
2585Tuples are a generalization of @std::pair@, in that they allow for arbitrary length, fixed-size aggregation of heterogeneous values.
2586Operations include @std::get<N>@ to extract values, @std::tie@ to create a tuple of references used for assignment, and lexicographic comparisons.
2587\CCseventeen proposes \emph{structured bindings}~\cite{Sutter15} to eliminate pre-declaring variables and use of @std::tie@ for binding the results.
2588This 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.
2589Furthermore, structured bindings are not a full replacement for @std::tie@, as it always declares new variables.
2590Like \CC, D provides tuples through a library variadic-template structure.
2591Go does not have tuples but supports MRVF.
2592Java'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.
2593Tuples are a fundamental abstraction in most functional programming languages, such as Standard ML~\cite{sml} and~\cite{Scala}, which decompose tuples using pattern matching.
2594
2595
2596\section{Conclusion and Future Work}
2597
2598The 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.
2599While 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.
2600The 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.
2601The contributions are a powerful type-system using parametric polymorphism and overloading, generic types, and tuples, which all have complex interactions.
2602The work is a challenging design, engineering, and implementation exercise.
2603On the surface, the project may appear as a rehash of similar mechanisms in \CC.
2604However, 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.
2605All of these new features are being used by the \CFA development-team to build the \CFA runtime-system.
2606Finally, we demonstrate that \CFA performance for some idiomatic cases is better than C and close to \CC, showing the design is practically applicable.
2607
2608There is ongoing work on a wide range of \CFA feature extensions, including arrays with size, exceptions, concurrent primitives, modules, and user-defined conversions.
2609(While all examples in the paper compile and run, a public beta-release of \CFA will take another 8--12 months to finalize these additional extensions.)
2610In addition, there are interesting future directions for the polymorphism design.
2611Notably, \CC template functions trade compile time and code bloat for optimal runtime of individual instantiations of polymorphic functions.
2612\CFA polymorphic functions use dynamic virtual-dispatch;
2613the runtime overhead of this approach is low, but not as low as inlining, and it may be beneficial to provide a mechanism for performance-sensitive code.
2614Two 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).
2615These approaches are not mutually exclusive and allow performance optimizations to be applied only when necessary, without suffering global code-bloat.
2616In general, we believe separate compilation, producing smaller code, works well with loaded hardware-caches, which may offset the benefit of larger inlined-code.
2617
2618
2619\section{Acknowledgments}
2620
2621The authors would like to recognize the design assistance of Glen Ditchfield, Richard Bilson, and Thierry Delisle on the features described in this paper, and thank Magnus Madsen for feedback in the writing.
2622%This work is supported in part by a corporate partnership with \grantsponsor{Huawei}{Huawei Ltd.}{http://www.huawei.com}, and Aaron Moss and Peter Buhr are funded by the \grantsponsor{Natural Sciences and Engineering Research Council} of Canada.
2623% the first author's \grantsponsor{NSERC-PGS}{NSERC PGS D}{http://www.nserc-crsng.gc.ca/Students-Etudiants/PG-CS/BellandPostgrad-BelletSuperieures_eng.asp} scholarship.
2624
2625
2626\bibliographystyle{plain}
2627\bibliography{pl}
2628
2629
2630\appendix
2631
2632\section{Benchmark Stack Implementation}
2633\label{sec:BenchmarkStackImplementation}
2634
2635\lstset{basicstyle=\linespread{0.9}\sf\small}
2636
2637Throughout, @/***/@ designates a counted redundant type annotation.
2638
2639\smallskip\noindent
2640\CFA
2641\begin{cfa}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
2642forall(otype T) struct stack_node {
2643        T value;
2644        stack_node(T) * next;
2645};
2646forall(otype T) void ?{}(stack(T) * s) { (&s->head){ 0 }; }
2647forall(otype T) void ?{}(stack(T) * s, stack(T) t) {
2648        stack_node(T) ** crnt = &s->head;
2649        for ( stack_node(T) * next = t.head; next; next = next->next ) {
2650                *crnt = ((stack_node(T) *)malloc()){ next->value }; /***/
2651                stack_node(T) * acrnt = *crnt;
2652                crnt = &acrnt->next;
2653        }
2654        *crnt = 0;
2655}
2656forall(otype T) stack(T) ?=?(stack(T) * s, stack(T) t) {
2657        if ( s->head == t.head ) return *s;
2658        clear(s);
2659        s{ t };
2660        return *s;
2661}
2662forall(otype T) void ^?{}(stack(T) * s) { clear(s); }
2663forall(otype T) _Bool empty(const stack(T) * s) { return s->head == 0; }
2664forall(otype T) void push(stack(T) * s, T value) {
2665        s->head = ((stack_node(T) *)malloc()){ value, s->head }; /***/
2666}
2667forall(otype T) T pop(stack(T) * s) {
2668        stack_node(T) * n = s->head;
2669        s->head = n->next;
2670        T x = n->value;
2671        ^n{};
2672        free(n);
2673        return x;
2674}
2675forall(otype T) void clear(stack(T) * s) {
2676        for ( stack_node(T) * next = s->head; next; ) {
2677                stack_node(T) * crnt = next;
2678                next = crnt->next;
2679                delete(crnt);
2680        }
2681        s->head = 0;
2682}
2683\end{cfa}
2684
2685\medskip\noindent
2686\CC
2687\begin{cfa}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
2688template<typename T> class stack {
2689        struct node {
2690                T value;
2691                node * next;
2692                node( const T & v, node * n = nullptr ) : value(v), next(n) {}
2693        };
2694        node * head;
2695        void copy(const stack<T>& o) {
2696                node ** crnt = &head;
2697                for ( node * next = o.head;; next; next = next->next ) {
2698                        *crnt = new node{ next->value }; /***/
2699                        crnt = &(*crnt)->next;
2700                }
2701                *crnt = nullptr;
2702        }
2703  public:
2704        stack() : head(nullptr) {}
2705        stack(const stack<T>& o) { copy(o); }
2706        stack(stack<T> && o) : head(o.head) { o.head = nullptr; }
2707        ~stack() { clear(); }
2708        stack & operator= (const stack<T>& o) {
2709                if ( this == &o ) return *this;
2710                clear();
2711                copy(o);
2712                return *this;
2713        }
2714        stack & operator= (stack<T> && o) {
2715                if ( this == &o ) return *this;
2716                head = o.head;
2717                o.head = nullptr;
2718                return *this;
2719        }
2720        bool empty() const { return head == nullptr; }
2721        void push(const T & value) { head = new node{ value, head };  /***/ }
2722        T pop() {
2723                node * n = head;
2724                head = n->next;
2725                T x = std::move(n->value);
2726                delete n;
2727                return x;
2728        }
2729        void clear() {
2730                for ( node * next = head; next; ) {
2731                        node * crnt = next;
2732                        next = crnt->next;
2733                        delete crnt;
2734                }
2735                head = nullptr;
2736        }
2737};
2738\end{cfa}
2739
2740\medskip\noindent
2741C
2742\begin{cfa}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
2743struct stack_node {
2744        void * value;
2745        struct stack_node * next;
2746};
2747struct stack new_stack() { return (struct stack){ NULL }; /***/ }
2748void copy_stack(struct stack * s, const struct stack * t, void * (*copy)(const void *)) {
2749        struct stack_node ** crnt = &s->head;
2750        for ( struct stack_node * next = t->head; next; next = next->next ) {
2751                *crnt = malloc(sizeof(struct stack_node)); /***/
2752                **crnt = (struct stack_node){ copy(next->value) }; /***/
2753                crnt = &(*crnt)->next;
2754        }
2755        *crnt = 0;
2756}
2757_Bool stack_empty(const struct stack * s) { return s->head == NULL; }
2758void push_stack(struct stack * s, void * value) {
2759        struct stack_node * n = malloc(sizeof(struct stack_node)); /***/
2760        *n = (struct stack_node){ value, s->head }; /***/
2761        s->head = n;
2762}
2763void * pop_stack(struct stack * s) {
2764        struct stack_node * n = s->head;
2765        s->head = n->next;
2766        void * x = n->value;
2767        free(n);
2768        return x;
2769}
2770void clear_stack(struct stack * s, void (*free_el)(void *)) {
2771        for ( struct stack_node * next = s->head; next; ) {
2772                struct stack_node * crnt = next;
2773                next = crnt->next;
2774                free_el(crnt->value);
2775                free(crnt);
2776        }
2777        s->head = NULL;
2778}
2779\end{cfa}
2780
2781\medskip\noindent
2782\CCV
2783\begin{cfa}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
2784stack::node::node( const object & v, node * n ) : value( v.new_copy() ), next( n ) {}
2785void stack::copy(const stack & o) {
2786        node ** crnt = &head;
2787        for ( node * next = o.head; next; next = next->next ) {
2788                *crnt = new node{ *next->value };
2789                crnt = &(*crnt)->next;
2790        }
2791        *crnt = nullptr;
2792}
2793stack::stack() : head(nullptr) {}
2794stack::stack(const stack & o) { copy(o); }
2795stack::stack(stack && o) : head(o.head) { o.head = nullptr; }
2796stack::~stack() { clear(); }
2797stack & stack::operator= (const stack & o) {
2798        if ( this == &o ) return *this;
2799        clear();
2800        copy(o);
2801        return *this;
2802}
2803stack & stack::operator= (stack && o) {
2804        if ( this == &o ) return *this;
2805        head = o.head;
2806        o.head = nullptr;
2807        return *this;
2808}
2809bool stack::empty() const { return head == nullptr; }
2810void stack::push(const object & value) { head = new node{ value, head }; /***/ }
2811ptr<object> stack::pop() {
2812        node * n = head;
2813        head = n->next;
2814        ptr<object> x = std::move(n->value);
2815        delete n;
2816        return x;
2817}
2818void stack::clear() {
2819        for ( node * next = head; next; ) {
2820                node * crnt = next;
2821                next = crnt->next;
2822                delete crnt;
2823        }
2824        head = nullptr;
2825}
2826\end{cfa}
2827
2828
2829\begin{comment}
2830
2831\subsubsection{bench.h}
2832(\texttt{bench.hpp} is similar.)
2833
2834\lstinputlisting{evaluation/bench.h}
2835
2836\subsection{C}
2837
2838\subsubsection{c-stack.h} ~
2839
2840\lstinputlisting{evaluation/c-stack.h}
2841
2842\subsubsection{c-stack.c} ~
2843
2844\lstinputlisting{evaluation/c-stack.c}
2845
2846\subsubsection{c-pair.h} ~
2847
2848\lstinputlisting{evaluation/c-pair.h}
2849
2850\subsubsection{c-pair.c} ~
2851
2852\lstinputlisting{evaluation/c-pair.c}
2853
2854\subsubsection{c-print.h} ~
2855
2856\lstinputlisting{evaluation/c-print.h}
2857
2858\subsubsection{c-print.c} ~
2859
2860\lstinputlisting{evaluation/c-print.c}
2861
2862\subsubsection{c-bench.c} ~
2863
2864\lstinputlisting{evaluation/c-bench.c}
2865
2866\subsection{\CFA}
2867
2868\subsubsection{cfa-stack.h} ~
2869
2870\lstinputlisting{evaluation/cfa-stack.h}
2871
2872\subsubsection{cfa-stack.c} ~
2873
2874\lstinputlisting{evaluation/cfa-stack.c}
2875
2876\subsubsection{cfa-print.h} ~
2877
2878\lstinputlisting{evaluation/cfa-print.h}
2879
2880\subsubsection{cfa-print.c} ~
2881
2882\lstinputlisting{evaluation/cfa-print.c}
2883
2884\subsubsection{cfa-bench.c} ~
2885
2886\lstinputlisting{evaluation/cfa-bench.c}
2887
2888\subsection{\CC}
2889
2890\subsubsection{cpp-stack.hpp} ~
2891
2892\lstinputlisting[language=c++]{evaluation/cpp-stack.hpp}
2893
2894\subsubsection{cpp-print.hpp} ~
2895
2896\lstinputlisting[language=c++]{evaluation/cpp-print.hpp}
2897
2898\subsubsection{cpp-bench.cpp} ~
2899
2900\lstinputlisting[language=c++]{evaluation/cpp-bench.cpp}
2901
2902\subsection{\CCV}
2903
2904\subsubsection{object.hpp} ~
2905
2906\lstinputlisting[language=c++]{evaluation/object.hpp}
2907
2908\subsubsection{cpp-vstack.hpp} ~
2909
2910\lstinputlisting[language=c++]{evaluation/cpp-vstack.hpp}
2911
2912\subsubsection{cpp-vstack.cpp} ~
2913
2914\lstinputlisting[language=c++]{evaluation/cpp-vstack.cpp}
2915
2916\subsubsection{cpp-vprint.hpp} ~
2917
2918\lstinputlisting[language=c++]{evaluation/cpp-vprint.hpp}
2919
2920\subsubsection{cpp-vbench.cpp} ~
2921
2922\lstinputlisting[language=c++]{evaluation/cpp-vbench.cpp}
2923\end{comment}
2924
2925\end{document}
2926
2927% Local Variables: %
2928% tab-width: 4 %
2929% compile-command: "make" %
2930% End: %
Note: See TracBrowser for help on using the repository browser.