source: doc/papers/general/Paper.tex @ c7ad609

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since c7ad609 was c7ad609, checked in by Peter A. Buhr <pabuhr@…>, 4 years ago

wordsmithing

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