source: doc/papers/general/Paper.tex @ 43c6dc82

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since 43c6dc82 was 43c6dc82, checked in by Aaron Moss <a3moss@…>, 4 years ago

First draft of 0/1 section of paper

  • Property mode set to 100644
File size: 117.6 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{rotating}
9\usepackage[usenames]{color}
10\usepackage{pslatex}                                    % reduce size of san serif font
11\usepackage[plainpages=false,pdfpagelabels,pdfpagemode=UseNone,pagebackref=true,breaklinks=true,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}
12
13\setlength{\textheight}{9in}
14%\oddsidemargin 0.0in
15\renewcommand{\topfraction}{0.8}                % float must be greater than X of the page before it is forced onto its own page
16\renewcommand{\bottomfraction}{0.8}             % float must be greater than X of the page before it is forced onto its own page
17\renewcommand{\floatpagefraction}{0.8}  % float must be greater than X of the page before it is forced onto its own page
18\renewcommand{\textfraction}{0.0}               % the entire page maybe devoted to floats with no text on the page at all
19
20\lefthyphenmin=4                                                % hyphen only after 4 characters
21\righthyphenmin=4
22
23% Names used in the document.
24
25\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
26\newcommand{\CFA}{\protect\CFAIcon} % safe for section/caption
27\newcommand{\CFL}{\textrm{Cforall}\xspace} % Cforall symbolic name
28\newcommand{\Celeven}{\textrm{C11}\xspace} % C11 symbolic name
29\newcommand{\CC}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
30\newcommand{\CCeleven}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
31\newcommand{\CCfourteen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
32\newcommand{\CCseventeen}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
33\newcommand{\CCtwenty}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name
34\newcommand{\CCV}{\rm C\kern-.1em\hbox{+\kern-.25em+}obj\xspace} % C++ virtual symbolic name
35\newcommand{\Csharp}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} % C# symbolic name
36
37%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
38
39\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
40\newcommand{\TODO}[1]{\textbf{TODO}: {\itshape #1}} % TODO included
41%\newcommand{\TODO}[1]{} % TODO elided
42
43% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
44% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
45% AFTER HYPERREF.
46%\DeclareTextCommandDefault{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}
47\renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
48
49\makeatletter
50% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
51% use rather than use \parident directly.
52\newlength{\parindentlnth}
53\setlength{\parindentlnth}{\parindent}
54
55\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
56\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
57
58\newlength{\gcolumnposn}                                % temporary hack because lstlisting does not handle tabs correctly
59\newlength{\columnposn}
60\setlength{\gcolumnposn}{2.75in}
61\setlength{\columnposn}{\gcolumnposn}
62\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}}}}
63\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
64
65% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
66% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
67% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
68\newcommand{\newtermFontInline}{\emph}
69\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
70\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
71\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
72
73% Latin abbreviation
74\newcommand{\abbrevFont}{\textit}       % set empty for no italics
75\newcommand{\EG}{\abbrevFont{e}.\abbrevFont{g}.}
76\newcommand*{\eg}{%
77        \@ifnextchar{,}{\EG}%
78                {\@ifnextchar{:}{\EG}%
79                        {\EG,\xspace}}%
80}%
81\newcommand{\IE}{\abbrevFont{i}.\abbrevFont{e}.}
82\newcommand*{\ie}{%
83        \@ifnextchar{,}{\IE}%
84                {\@ifnextchar{:}{\IE}%
85                        {\IE,\xspace}}%
86}%
87\newcommand{\ETC}{\abbrevFont{etc}}
88\newcommand*{\etc}{%
89        \@ifnextchar{.}{\ETC}%
90        {\ETC\xspace}%
91}%
92\newcommand{\ETAL}{\abbrevFont{et}\hspace{2pt}\abbrevFont{al}}
93\newcommand*{\etal}{%
94        \@ifnextchar{.}{\protect\ETAL}%
95                {\abbrevFont{\protect\ETAL}.\xspace}%
96}%
97\newcommand{\VIZ}{\abbrevFont{viz}}
98\newcommand*{\viz}{%
99        \@ifnextchar{.}{\VIZ}%
100                {\abbrevFont{\VIZ}.\xspace}%
101}%
102\makeatother
103
104\newenvironment{cquote}{%
105        \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=4pt\parsep=0pt\leftmargin=\parindent\rightmargin\leftmargin}%
106        \item\relax
107}{%
108        \endlist
109}% cquote
110
111% CFA programming language, based on ANSI C (with some gcc additions)
112\lstdefinelanguage{CFA}[ANSI]{C}{
113        morekeywords={
114                _Alignas, _Alignof, __alignof, __alignof__, asm, __asm, __asm__, _At, __attribute,
115                __attribute__, auto, _Bool, catch, catchResume, choose, _Complex, __complex, __complex__,
116                __const, __const__, disable, dtype, enable, __extension__, fallthrough, fallthru,
117                finally, forall, ftype, _Generic, _Imaginary, inline, __label__, lvalue, _Noreturn, one_t,
118                otype, restrict, _Static_assert, throw, throwResume, trait, try, ttype, typeof, __typeof,
119                __typeof__, virtual, with, zero_t},
120        moredirectives={defined,include_next}%
121}%
122
123\lstset{
124language=CFA,
125columns=fullflexible,
126basicstyle=\linespread{0.9}\sf,                                                 % reduce line spacing and use sanserif font
127stringstyle=\tt,                                                                                % use typewriter font
128tabsize=5,                                                                                              % N space tabbing
129xleftmargin=\parindentlnth,                                                             % indent code to paragraph indentation
130%mathescape=true,                                                                               % LaTeX math escape in CFA code $...$
131escapechar=\$,                                                                                  % LaTeX escape in CFA code
132keepspaces=true,                                                                                %
133showstringspaces=false,                                                                 % do not show spaces with cup
134showlines=true,                                                                                 % show blank lines at end of code
135aboveskip=4pt,                                                                                  % spacing above/below code block
136belowskip=3pt,
137% replace/adjust listing characters that look bad in sanserif
138literate={-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.1ex}}}}1 {^}{\raisebox{0.6ex}{$\scriptscriptstyle\land\,$}}1
139        {~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
140        {<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2 {->}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.8ex}{0.075ex}}}\kern-0.2ex\textgreater}2,
141moredelim=**[is][\color{red}]{`}{`},
142}% lstset
143
144% inline code @...@
145\lstMakeShortInline@%
146
147\lstnewenvironment{cfa}[1][]
148{\lstset{#1}}
149{}
150\lstnewenvironment{C++}[1][]                            % use C++ style
151{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{`}{`},#1}\lstset{#1}}
152{}
153
154
155\title{Generic and Tuple Types with Efficient Dynamic Layout in \protect\CFA}
156
157\author{Aaron Moss, Robert Schluntz, Peter Buhr}
158% \email{a3moss@uwaterloo.ca}
159% \email{rschlunt@uwaterloo.ca}
160% \email{pabuhr@uwaterloo.ca}
161% \affiliation{%
162%       \institution{University of Waterloo}
163%       \department{David R. Cheriton School of Computer Science}
164%       \streetaddress{Davis Centre, University of Waterloo}
165%       \city{Waterloo}
166%       \state{ON}
167%       \postcode{N2L 3G1}
168%       \country{Canada}
169% }
170
171%\terms{generic, tuple, variadic, types}
172%\keywords{generic types, tuple types, variadic types, polymorphic functions, C, Cforall}
173
174\begin{document}
175\maketitle
176
177
178\begin{abstract}
179The 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.
180This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
181Nonetheless, C, first standardized over thirty years ago, lacks many features that make programming in more modern languages safer and more productive.
182The 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.
183Prior 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.
184Specifically, \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.
185This 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.
186\end{abstract}
187
188
189\section{Introduction and Background}
190
191The 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.
192This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more.
193The 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.
194The top 3 rankings over the past 30 years are:
195\lstDeleteShortInline@%
196\begin{center}
197\setlength{\tabcolsep}{10pt}
198\begin{tabular}{@{}rccccccc@{}}
199                & 2017  & 2012  & 2007  & 2002  & 1997  & 1992  & 1987          \\ \hline
200Java    & 1             & 1             & 1             & 1             & 12    & -             & -                     \\
201\Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \Textbf{1}& \Textbf{1}    \\
202\CC             & 3             & 3             & 3             & 3             & 2             & 2             & 4                     \\
203\end{tabular}
204\end{center}
205\lstMakeShortInline@%
206Love it or hate it, C is extremely popular, highly used, and one of the few systems languages.
207In many cases, \CC is often used solely as a better C.
208Nonetheless, C, first standardized over thirty years ago, lacks many features that make programming in more modern languages safer and more productive.
209
210\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.
211The four key design goals for \CFA~\cite{Bilson03} are:
212(1) The behaviour of standard C code must remain the same when translated by a \CFA compiler as when translated by a C compiler;
213(2) Standard C code must be as fast and as small when translated by a \CFA compiler as when translated by a C compiler;
214(3) \CFA code must be at least as portable as standard C code;
215(4) Extensions introduced by \CFA must be translated in the most efficient way possible.
216These 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.
217\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.
218
219\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).
220Ultimately, a compiler is necessary for advanced features and optimal performance.
221
222This 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.
223Specifically, 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.
224The new constructs are empirically compared with both standard C and \CC; the results show the new design is comparable in performance.
225
226
227\subsection{Polymorphic Functions}
228\label{sec:poly-fns}
229
230\CFA{}\hspace{1pt}'s polymorphism was originally formalized by Ditchfield~\cite{Ditchfield92}, and first implemented by Bilson~\cite{Bilson03}.
231The 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):
232\begin{lstlisting}
233`forall( otype T )` T identity( T val ) { return val; }
234int forty_two = identity( 42 );                         $\C{// T is bound to int, forty\_two == 42}$
235\end{lstlisting}
236The @identity@ function above can be applied to any complete \newterm{object type} (or @otype@).
237The 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.
238The \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.
239If this extra information is not needed, \eg for a pointer, the type parameter can be declared as a \newterm{data type} (or @dtype@).
240
241In \CFA, the polymorphism runtime-cost is spread over each polymorphic call, due to passing more arguments to polymorphic functions;
242the experiments in Section~\ref{sec:eval} show this overhead is similar to \CC virtual-function calls.
243A design advantage is that, unlike \CC template-functions, \CFA polymorphic-functions are compatible with C \emph{separate compilation}, preventing compilation and code bloat.
244
245Since 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.
246For example, the function @twice@ can be defined using the \CFA syntax for operator overloading:
247\begin{lstlisting}
248forall( otype T `| { T ?+?(T, T); }` ) T twice( T x ) { return x + x; } $\C{// ? denotes operands}$
249int val = twice( twice( 3.7 ) );
250\end{lstlisting}
251which works for any type @T@ with a matching addition operator.
252The 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@.
253There 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.
254The first approach has a late conversion from @double@ to @int@ on the final assignment, while the second has an eager conversion to @int@.
255\CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach, which corresponds with C-programmer intuition.
256
257Crucial to the design of a new programming language are the libraries to access thousands of external software features.
258Like \CC, \CFA inherits a massive compatible library-base, where other programming languages must rewrite or provide fragile inter-language communication with C.
259A simple example is leveraging the existing type-unsafe (@void *@) C @bsearch@ to binary search a sorted floating-point array:
260\begin{lstlisting}
261void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
262                                int (* compar)( const void *, const void * ));
263int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 :
264                                *(double *)t2 < *(double *)t1 ? 1 : 0; }
265double key = 5.0, vals[10] = { /* 10 sorted floating-point values */ };
266double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp );      $\C{// search sorted array}$
267\end{lstlisting}
268which can be augmented simply with a generalized, type-safe, \CFA-overloaded wrappers:
269\begin{lstlisting}
270forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) {
271        int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ }
272        return (T *)bsearch( &key, arr, size, sizeof(T), comp ); }
273forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) {
274        T * result = bsearch( key, arr, size ); $\C{// call first version}$
275        return result ? result - arr : size; }  $\C{// pointer subtraction includes sizeof(T)}$
276double * val = bsearch( 5.0, vals, 10 );        $\C{// selection based on return type}$
277int posn = bsearch( 5.0, vals, 10 );
278\end{lstlisting}
279The nested function @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
280Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
281As well, an alternate kind of return is made available: position versus pointer to found element.
282\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@.
283
284\CFA has replacement libraries condensing hundreds of existing C functions into tens of \CFA overloaded functions, all without rewriting the actual computations.
285For example, it is possible to write a type-safe \CFA wrapper @malloc@ based on the C @malloc@:
286\begin{lstlisting}
287forall( dtype T | sized(T) ) T * malloc( void ) { return (T *)malloc( sizeof(T) ); }
288int * ip = malloc();                                            $\C{// select type and size from left-hand side}$
289double * dp = malloc();
290struct S {...} * sp = malloc();
291\end{lstlisting}
292where the return type supplies the type/size of the allocation, which is impossible in most type systems.
293
294Call-site inferencing and nested functions provide a localized form of inheritance.
295For example, the \CFA @qsort@ only sorts in ascending order using @<@.
296However, it is trivial to locally change this behaviour:
297\begin{lstlisting}
298forall( otype T | { int ?<?( T, T ); } ) void qsort( const T * arr, size_t size ) { /* use C qsort */ }
299{       int ?<?( double x, double y ) { return x `>` y; }       $\C{// locally override behaviour}$
300        qsort( vals, size );                                    $\C{// descending sort}$
301}
302\end{lstlisting}
303Within the block, the nested version of @?<?@ performs @?>?@ and this local version overrides the built-in @?<?@ so it is passed to @qsort@.
304Hence, programmers can easily form local environments, adding and modifying appropriate functions, to maximize reuse of other existing functions and types.
305
306Finally, \CFA allows variable overloading:
307\begin{lstlisting}
308short int MAX = ...;   int MAX = ...;  double MAX = ...;
309short int s = MAX;    int i = MAX;    double d = MAX;   $\C{// select correct MAX}$
310\end{lstlisting}
311Here, the single name @MAX@ replaces all the C type-specific names: @SHRT_MAX@, @INT_MAX@, @DBL_MAX@.
312
313\subsection{Traits}
314
315\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:
316\begin{lstlisting}
317trait summable( otype T ) {
318        void ?{}( T *, zero_t );                                $\C{// constructor from 0 literal}$
319        T ?+?( T, T );                                                  $\C{// assortment of additions}$
320        T ?+=?( T *, T );
321        T ++?( T * );
322        T ?++( T * ); };
323forall( otype T `| summable( T )` ) T sum( T a[$\,$], size_t size ) {  // use trait
324        `T` total = { `0` };                                    $\C{// instantiate T from 0 by calling its constructor}$
325        for ( unsigned int i = 0; i < size; i += 1 ) total `+=` a[i]; $\C{// select appropriate +}$
326        return total; }
327\end{lstlisting}
328
329In 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:
330\begin{lstlisting}
331trait otype( dtype T | sized(T) ) {  // sized is a pseudo-trait for types with known size and alignment
332        void ?{}( T * );                                                $\C{// default constructor}$
333        void ?{}( T *, T );                                             $\C{// copy constructor}$
334        void ?=?( T *, T );                                             $\C{// assignment operator}$
335        void ^?{}( T * ); };                                    $\C{// destructor}$
336\end{lstlisting}
337Given 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.
338
339In 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.
340Hence, trait names play no part in type equivalence;
341the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
342Nevertheless, trait names form a logical subtype-hierarchy with @dtype@ at the top, where traits often contain overlapping assertions, \eg operator @+@.
343Traits are used like interfaces in Java or abstract base-classes in \CC, but without the nominal inheritance-relationships.
344Instead, 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.
345Hence, 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.
346(Nominal inheritance can be approximated with traits using marker variables or functions, as is done in Go.)
347
348% Nominal inheritance can be simulated with traits using marker variables or functions:
349% \begin{lstlisting}
350% trait nominal(otype T) {
351%     T is_nominal;
352% };
353% int is_nominal;                                                               $\C{// int now satisfies the nominal trait}$
354% \end{lstlisting}
355%
356% 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:
357% \begin{lstlisting}
358% trait pointer_like(otype Ptr, otype El) {
359%     lvalue El *?(Ptr);                                                $\C{// Ptr can be dereferenced into a modifiable value of type El}$
360% }
361% struct list {
362%     int value;
363%     list * next;                                                              $\C{// may omit "struct" on type names as in \CC}$
364% };
365% typedef list * list_iterator;
366%
367% lvalue int *?( list_iterator it ) { return it->value; }
368% \end{lstlisting}
369% 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@).
370% 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.
371
372
373\section{Generic Types}
374
375One of the known shortcomings of standard C is that it does not provide reusable type-safe abstractions for generic data structures and algorithms.
376Broadly speaking, there are three approaches to implement abstract data-structures in C.
377One approach is to write bespoke data-structures for each context in which they are needed.
378While 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.
379A 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.
380However, 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.
381A 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.
382Furthermore, writing and using preprocessor macros can be unnatural and inflexible.
383
384\CC, Java, and other languages use \newterm{generic types} to produce type-safe abstract data-types.
385\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.
386However, for known concrete parameters, the generic-type definition can be inlined, like \CC templates.
387
388A 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:
389\begin{lstlisting}
390forall( otype R, otype S ) struct pair {
391        R first;
392        S second;
393};
394forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; }
395forall( dtype F, otype T ) T value_p( pair( F *, T * ) p ) { return * p.second; }
396pair( const char *, int ) p = { "magic", 42 };
397int magic = value( p );
398pair( void *, int * ) q = { 0, &p.second };
399magic = value_p( q );
400double d = 1.0;
401pair( double *, double * ) r = { &d, &d };
402d = value_p( r );
403\end{lstlisting}
404
405\CFA classifies generic types as either \newterm{concrete} or \newterm{dynamic}.
406Concrete types have a fixed memory layout regardless of type parameters, while dynamic types vary in memory layout depending on their type parameters.
407A type may have polymorphic parameters but still be concrete, called \newterm{dtype-static}.
408Polymorphic 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.
409
410\CFA generic types also allow checked argument-constraints.
411For example, the following declaration of a sorted set-type ensures the set key supports equality and relational comparison:
412\begin{lstlisting}
413forall( otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); } ) struct sorted_set;
414\end{lstlisting}
415
416
417\subsection{Concrete Generic-Types}
418
419The \CFA translator template-expands concrete generic-types into new structure types, affording maximal inlining.
420To 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.
421A 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.
422For example, the concrete instantiation for @pair( const char *, int )@ is:
423\begin{lstlisting}
424struct _pair_conc1 {
425        const char * first;
426        int second;
427};
428\end{lstlisting}
429
430A concrete generic-type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations.
431In 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:
432\begin{lstlisting}
433struct _pair_conc0 {
434        void * first;
435        void * second;
436};
437\end{lstlisting}
438
439
440\subsection{Dynamic Generic-Types}
441
442Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types.
443As 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.
444Dynamic generic-types also have an \newterm{offset array} containing structure-member offsets.
445A dynamic generic-union needs no such offset array, as all members are at offset 0, but size and alignment are still necessary.
446Access 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.
447
448The offset arrays are statically generated where possible.
449If 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;
450if 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.
451As 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 )@.
452The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) }@.
453
454In some cases the offset arrays cannot be statically generated.
455For 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.
456\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.
457The \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.
458These 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).
459Results of these layout functions are cached so that they are only computed once per type per function. %, as in the example below for @pair@.
460Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature.
461For 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.
462This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function.
463
464Whether a type is concrete, dtype-static, or dynamic is decided solely on the @forall@'s type parameters.
465This 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.
466If 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.
467
468
469\subsection{Applications}
470\label{sec:generic-apps}
471
472The reuse of dtype-static structure instantiations enables useful programming patterns at zero runtime cost.
473The 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@:
474\begin{lstlisting}
475forall(dtype T) int lexcmp( pair( T *, T * ) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {
476        return cmp( a->first, b->first ) ? : cmp( a->second, b->second );
477}
478\end{lstlisting}
479Since @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.
480
481Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \newterm{tag-structures}.
482Sometimes information is only used for type-checking and can be omitted at runtime, \eg:
483\begin{lstlisting}
484forall(dtype Unit) struct scalar { unsigned long value; };
485struct metres {};
486struct litres {};
487
488forall(dtype U) scalar(U) ?+?( scalar(U) a, scalar(U) b ) {
489        return (scalar(U)){ a.value + b.value };
490}
491scalar(metres) half_marathon = { 21093 };
492scalar(litres) swimming_pool = { 2500000 };
493scalar(metres) marathon = half_marathon + half_marathon;
494scalar(litres) two_pools = swimming_pool + swimming_pool;
495marathon + swimming_pool;                                       $\C{// compilation ERROR}$
496\end{lstlisting}
497@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 @?+?@.
498These implementations may even be separately compiled, unlike \CC template functions.
499However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume.
500
501
502\section{Tuples}
503\label{sec:tuples}
504
505In many languages, functions can return at most one value;
506however, many operations have multiple outcomes, some exceptional.
507Consider C's @div@ and @remquo@ functions, which return the quotient and remainder for a division of integer and floating-point values, respectively.
508\begin{lstlisting}
509typedef struct { int quo, rem; } div_t;         $\C{// from include stdlib.h}$
510div_t div( int num, int den );
511double remquo( double num, double den, int * quo );
512div_t qr = div( 13, 5 );                                        $\C{// return quotient/remainder aggregate}$
513int q;
514double r = remquo( 13.5, 5.2, &q );                     $\C{// return remainder, alias quotient}$
515\end{lstlisting}
516@div@ aggregates the quotient/remainder in a structure, while @remquo@ aliases a parameter to an argument.
517Both approaches are awkward.
518Alternatively, a programming language can directly support returning multiple values, \eg in \CFA:
519\begin{lstlisting}
520[ int, int ] div( int num, int den );           $\C{// return two integers}$
521[ double, double ] div( double num, double den ); $\C{// return two doubles}$
522int q, r;                                                                       $\C{// overloaded variable names}$
523double q, r;
524[ q, r ] = div( 13, 5 );                                        $\C{// select appropriate div and q, r}$
525[ q, r ] = div( 13.5, 5.2 );                            $\C{// assign into tuple}$
526\end{lstlisting}
527Clearly, this approach is straightforward to understand and use;
528therefore, why do few programming languages support this obvious feature or provide it awkwardly?
529The answer is that there are complex consequences that cascade through multiple aspects of the language, especially the type-system.
530This section show these consequences and how \CFA handles them.
531
532
533\subsection{Tuple Expressions}
534
535The addition of multiple-return-value functions (MRVF) are useless without a syntax for accepting multiple values at the call-site.
536The simplest mechanism for capturing the return values is variable assignment, allowing the values to be retrieved directly.
537As 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}.
538
539However, 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:
540\begin{lstlisting}
541printf( "%d %d\n", div( 13, 5 ) );                      $\C{// return values seperated into arguments}$
542\end{lstlisting}
543Here, the values returned by @div@ are composed with the call to @printf@ by flattening the tuple into separate arguments.
544However, the \CFA type-system must support significantly more complex composition:
545\begin{lstlisting}
546[ int, int ] foo$\(_1\)$( int );                        $\C{// overloaded foo functions}$
547[ double ] foo$\(_2\)$( int );
548void bar( int, double, double );
549bar( foo( 3 ), foo( 3 ) );
550\end{lstlisting}
551The 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.
552No combination of @foo@s are an exact match with @bar@'s parameters, so the resolver applies C conversions.
553The 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.
554
555
556\subsection{Tuple Variables}
557
558An important observation from function composition is that new variable names are not required to initialize parameters from an MRVF.
559\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:
560\begin{lstlisting}
561[ int, int ] qr = div( 13, 5 );                         $\C{// tuple-variable declaration and initialization}$
562[ double, double ] qr = div( 13.5, 5.2 );
563\end{lstlisting}
564where the tuple variable-name serves the same purpose as the parameter name(s).
565Tuple variables can be composed of any types, except for array types, since array sizes are generally unknown in C.
566
567One way to access the tuple-variable components is with assignment or composition:
568\begin{lstlisting}
569[ q, r ] = qr;                                                          $\C{// access tuple-variable components}$
570printf( "%d %d\n", qr );
571\end{lstlisting}
572\CFA also supports \newterm{tuple indexing} to access single components of a tuple expression:
573\begin{lstlisting}
574[int, int] * p = &qr;                                           $\C{// tuple pointer}$
575int rem = qr`.1`;                                                       $\C{// access remainder}$
576int quo = div( 13, 5 )`.0`;                                     $\C{// access quotient}$
577p`->0` = 5;                                                                     $\C{// change quotient}$
578bar( qr`.1`, qr );                                                      $\C{// pass remainder and quotient/remainder}$
579rem = [div( 13, 5 ), 42]`.0.1`;                         $\C{// access 2nd component of 1st component of tuple expression}$
580\end{lstlisting}
581
582
583\subsection{Flattening and Restructuring}
584
585In function call contexts, tuples support implicit flattening and restructuring conversions.
586Tuple flattening recursively expands a tuple into the list of its basic components.
587Tuple structuring packages a list of expressions into a value of tuple type, \eg:
588%\lstDeleteShortInline@%
589%\par\smallskip
590%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
591\begin{lstlisting}
592int f( int, int );
593int g( [int, int] );
594int h( int, [int, int] );
595[int, int] x;
596int y;
597f( x );                 $\C{// flatten}$
598g( y, 10 );             $\C{// structure}$
599h( x, y );              $\C{// flatten and structure}$
600\end{lstlisting}
601%\end{lstlisting}
602%&
603%\begin{lstlisting}
604%\end{tabular}
605%\smallskip\par\noindent
606%\lstMakeShortInline@%
607In the call to @f@, @x@ is implicitly flattened so the components of @x@ are passed as the two arguments.
608In 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@.
609Finally, 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]@.
610The 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.
611
612
613\subsection{Tuple Assignment}
614
615An assignment where the left side is a tuple type is called \newterm{tuple assignment}.
616There 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.
617%\lstDeleteShortInline@%
618%\par\smallskip
619%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
620\begin{lstlisting}
621int x = 10;
622double y = 3.5;
623[int, double] z;
624z = [x, y];                                                                     $\C{// multiple assignment}$
625[x, y] = z;                                                                     $\C{// multiple assignment}$
626z = 10;                                                                         $\C{// mass assignment}$
627[y, x] = 3.14;                                                          $\C{// mass assignment}$
628\end{lstlisting}
629%\end{lstlisting}
630%&
631%\begin{lstlisting}
632%\end{tabular}
633%\smallskip\par\noindent
634%\lstMakeShortInline@%
635Both kinds of tuple assignment have parallel semantics, so that each value on the left and right side is evaluated before any assignments occur.
636As 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]@.
637This 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.
638For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, yielding @y == 3.14@ and @x == 3@;
639whereas, C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, yielding @3@ in @y@ and @x@.
640Finally, 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.
641This example shows mass, multiple, and cascading assignment used in one expression:
642\begin{lstlisting}
643void f( [int, int] );
644f( [x, y] = z = 1.5 );                                          $\C{// assignments in parameter list}$
645\end{lstlisting}
646
647
648\subsection{Member Access}
649
650It is also possible to access multiple fields from a single expression using a \newterm{member-access}.
651The result is a single tuple-valued expression whose type is the tuple of the types of the members, \eg:
652\begin{lstlisting}
653struct S { int x; double y; char * z; } s;
654s.[x, y, z] = 0;
655\end{lstlisting}
656Here, the mass assignment sets all members of @s@ to zero.
657Since 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).
658%\lstDeleteShortInline@%
659%\par\smallskip
660%\begin{tabular}{@{}l@{\hspace{1.5\parindent}}||@{\hspace{1.5\parindent}}l@{}}
661\begin{lstlisting}
662[int, int, long, double] x;
663void f( double, long );
664x.[0, 1] = x.[1, 0];                                            $\C{// rearrange: [x.0, x.1] = [x.1, x.0]}$
665f( x.[0, 3] );                                                          $\C{// drop: f(x.0, x.3)}$
666[int, int, int] y = x.[2, 0, 2];                        $\C{// duplicate: [y.0, y.1, y.2] = [x.2, x.0.x.2]}$
667\end{lstlisting}
668%\end{lstlisting}
669%&
670%\begin{lstlisting}
671%\end{tabular}
672%\smallskip\par\noindent
673%\lstMakeShortInline@%
674It is also possible for a member access to contain other member accesses, \eg:
675\begin{lstlisting}
676struct A { double i; int j; };
677struct B { int * k; short l; };
678struct C { int x; A y; B z; } v;
679v.[x, y.[i, j], z.k];                                           $\C{// [v.x, [v.y.i, v.y.j], v.z.k]}$
680\end{lstlisting}
681
682
683\begin{comment}
684\subsection{Casting}
685
686In C, the cast operator is used to explicitly convert between types.
687In \CFA, the cast operator has a secondary use as type ascription.
688That 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:
689\begin{lstlisting}
690int f();     // (1)
691double f()// (2)
692
693f();       // ambiguous - (1),(2) both equally viable
694(int)f()// choose (2)
695\end{lstlisting}
696
697Since casting is a fundamental operation in \CFA, casts should be given a meaningful interpretation in the context of tuples.
698Taking a look at standard C provides some guidance with respect to the way casts should work with tuples:
699\begin{lstlisting}
700int f();
701void g();
702
703(void)f()// (1)
704(int)g()// (2)
705\end{lstlisting}
706In C, (1) is a valid cast, which calls @f@ and discards its result.
707On the other hand, (2) is invalid, because @g@ does not produce a result, so requesting an @int@ to materialize from nothing is nonsensical.
708Generalizing 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.
709
710Formally, 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$.
711Excess 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.
712This approach follows naturally from the way that a cast to @void@ works in C.
713
714For example, in
715\begin{lstlisting}
716[int, int, int] f();
717[int, [int, int], int] g();
718
719([int, double])f();           $\C{// (1)}$
720([int, int, int])g();         $\C{// (2)}$
721([void, [int, int]])g();      $\C{// (3)}$
722([int, int, int, int])g();    $\C{// (4)}$
723([int, [int, int, int]])g()$\C{// (5)}$
724\end{lstlisting}
725
726(1) discards the last element of the return value and converts the second element to @double@.
727Since @int@ is effectively a 1-element tuple, (2) discards the second component of the second element of the return value of @g@.
728If @g@ is free of side effects, this expression is equivalent to @[(int)(g().0), (int)(g().1.0), (int)(g().2)]@.
729Since @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)]@).
730
731Note 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.}.
732As such, (4) is invalid because the cast target type contains 4 components, while the source type contains only 3.
733Similarly, (5) is invalid because the cast @([int, int, int])(g().1)@ is invalid.
734That is, it is invalid to cast @[int, int]@ to @[int, int, int]@.
735\end{comment}
736
737
738\subsection{Polymorphism}
739
740Tuples also integrate with \CFA polymorphism as a kind of generic type.
741Due 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:
742\begin{lstlisting}
743forall(otype T, dtype U) void f( T x, U * y );
744f( [5, "hello"] );
745\end{lstlisting}
746where @[5, "hello"]@ is flattened, giving argument list @5, "hello"@, and @T@ binds to @int@ and @U@ binds to @const char@.
747Tuples, however, may contain polymorphic components.
748For example, a plus operator can be written to add two triples together.
749\begin{lstlisting}
750forall(otype T | { T ?+?( T, T ); }) [T, T, T] ?+?( [T, T, T] x, [T, T, T] y ) {
751        return [x.0 + y.0, x.1 + y.1, x.2 + y.2];
752}
753[int, int, int] x;
754int i1, i2, i3;
755[i1, i2, i3] = x + ([10, 20, 30]);
756\end{lstlisting}
757
758Flattening and restructuring conversions are also applied to tuple types in polymorphic type assertions.
759\begin{lstlisting}
760int f( [int, double], double );
761forall(otype T, otype U | { T f( T, U, U ); }) void g( T, U );
762g( 5, 10.21 );
763\end{lstlisting}
764Hence, function parameter and return lists are flattened for the purposes of type unification allowing the example to pass expression resolution.
765This relaxation is possible by extending the thunk scheme described by Bilson~\cite{Bilson03}.
766Whenever 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:
767\begin{lstlisting}
768int _thunk( int _p0, double _p1, double _p2 ) { return f( [_p0, _p1], _p2 ); }
769\end{lstlisting}
770so the thunk provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
771These thunks take advantage of GCC C nested-functions to produce closures that have the usual function-pointer signature.
772
773
774\subsection{Variadic Tuples}
775\label{sec:variadic-tuples}
776
777To define variadic functions, \CFA adds a new kind of type parameter, @ttype@ (tuple type).
778Matching against a @ttype@ parameter consumes all remaining argument components and packages them into a tuple, binding to the resulting tuple of types.
779In 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.
780As such, @ttype@ variables are also called \newterm{argument packs}.
781
782Like variadic templates, the main way to manipulate @ttype@ polymorphic functions is via recursion.
783Since nothing is known about a parameter pack by default, assertion parameters are key to doing anything meaningful.
784Unlike variadic templates, @ttype@ polymorphic functions can be separately compiled.
785For example, a generalized @sum@ function written using @ttype@:
786\begin{lstlisting}
787int sum$\(_0\)$() { return 0; }
788forall(ttype Params | { int sum( Params ); } ) int sum$\(_1\)$( int x, Params rest ) {
789        return x + sum( rest );
790}
791sum( 10, 20, 30 );
792\end{lstlisting}
793Since @sum@\(_0\) does not accept any arguments, it is not a valid candidate function for the call @sum(10, 20, 30)@.
794In 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]@.
795The process continues unitl @Params@ is bound to @[]@, requiring an assertion @int sum()@, which matches @sum@\(_0\) and terminates the recursion.
796Effectively, 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))@.
797
798It is reasonable to take the @sum@ function a step further to enforce a minimum number of arguments:
799\begin{lstlisting}
800int sum( int x, int y ) { return x + y; }
801forall(ttype Params | { int sum( int, Params ); } ) int sum( int x, int y, Params rest ) {
802        return sum( x + y, rest );
803}
804\end{lstlisting}
805One more step permits the summation of any summable type with all arguments of the same type:
806\begin{lstlisting}
807trait summable(otype T) {
808        T ?+?( T, T );
809};
810forall(otype R | summable( R ) ) R sum( R x, R y ) {
811        return x + y;
812}
813forall(otype R, ttype Params | summable(R) | { R sum(R, Params); } ) R sum(R x, R y, Params rest) {
814        return sum( x + y, rest );
815}
816\end{lstlisting}
817Unlike C variadic functions, it is unnecessary to hard code the number and expected types.
818Furthermore, this code is extendable for any user-defined type with a @?+?@ operator.
819Summing arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators.
820
821It is also possible to write a type-safe variadic print function to replace @printf@:
822\begin{lstlisting}
823struct S { int x, y; };
824forall(otype T, ttype Params | { void print(T); void print(Params); }) void print(T arg, Params rest) {
825        print(arg);  print(rest);
826}
827void print( char * x ) { printf( "%s", x ); }
828void print( int x ) { printf( "%d", x ); }
829void print( S s ) { print( "{ ", s.x, ",", s.y, " }" ); }
830print( "s = ", (S){ 1, 2 }, "\n" );
831\end{lstlisting}
832This example showcases a variadic-template-like decomposition of the provided argument list.
833The individual @print@ functions allow printing a single element of a type.
834The polymorphic @print@ allows printing any list of types, where as each individual type has a @print@ function.
835The individual print functions can be used to build up more complicated @print@ functions, such as @S@, which cannot be done with @printf@ in C.
836
837Finally, it is possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions.
838For example, it is possible to write @new@ as a library function:
839\begin{lstlisting}
840forall( otype R, otype S ) void ?{}( pair(R, S) *, R, S );
841forall( dtype T, ttype Params | sized(T) | { void ?{}( T *, Params ); } ) T * new( Params p ) {
842        return ((T *)malloc()){ p };                    $\C{// construct into result of malloc}$
843}
844pair( int, char ) * x = new( 42, '!' );
845\end{lstlisting}
846The @new@ function provides the combination of type-safe @malloc@ with a \CFA constructor call, making it impossible to forget constructing dynamically allocated objects.
847This function provides the type-safety of @new@ in \CC, without the need to specify the allocated type again, thanks to return-type inference.
848
849
850\subsection{Implementation}
851
852Tuples are implemented in the \CFA translator via a transformation into \newterm{generic types}.
853For each $N$, the first time an $N$-tuple is seen in a scope a generic type with $N$ type parameters is generated, \eg:
854\begin{lstlisting}
855[int, int] f() {
856        [double, double] x;
857        [int, double, int] y;
858}
859\end{lstlisting}
860is transformed into:
861\begin{lstlisting}
862forall(dtype T0, dtype T1 | sized(T0) | sized(T1)) struct _tuple2 {
863        T0 field_0;                                                             $\C{// generated before the first 2-tuple}$
864        T1 field_1;
865};
866_tuple2(int, int) f() {
867        _tuple2(double, double) x;
868        forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2)) struct _tuple3 {
869                T0 field_0;                                                     $\C{// generated before the first 3-tuple}$
870                T1 field_1;
871                T2 field_2;
872        };
873        _tuple3(int, double, int) y;
874}
875\end{lstlisting}
876\begin{sloppypar}
877Tuple expressions are then simply converted directly into compound literals, \eg @[5, 'x', 1.24]@ becomes @(_tuple3(int, char, double)){ 5, 'x', 1.24 }@.
878\end{sloppypar}
879
880\begin{comment}
881Since tuples are essentially structures, tuple indexing expressions are just field accesses:
882\begin{lstlisting}
883void f(int, [double, char]);
884[int, double] x;
885
886x.0+x.1;
887printf("%d %g\n", x);
888f(x, 'z');
889\end{lstlisting}
890Is transformed into:
891\begin{lstlisting}
892void f(int, _tuple2(double, char));
893_tuple2(int, double) x;
894
895x.field_0+x.field_1;
896printf("%d %g\n", x.field_0, x.field_1);
897f(x.field_0, (_tuple2){ x.field_1, 'z' });
898\end{lstlisting}
899Note that due to flattening, @x@ used in the argument position is converted into the list of its fields.
900In the call to @f@, the second and third argument components are structured into a tuple argument.
901Similarly, tuple member expressions are recursively expanded into a list of member access expressions.
902
903Expressions that may contain side effects are made into \newterm{unique expressions} before being expanded by the flattening conversion.
904Each unique expression is assigned an identifier and is guaranteed to be executed exactly once:
905\begin{lstlisting}
906void g(int, double);
907[int, double] h();
908g(h());
909\end{lstlisting}
910Internally, this expression is converted to two variables and an expression:
911\begin{lstlisting}
912void g(int, double);
913[int, double] h();
914
915_Bool _unq0_finished_ = 0;
916[int, double] _unq0;
917g(
918        (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).0,
919        (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).1,
920);
921\end{lstlisting}
922Since argument evaluation order is not specified by the C programming language, this scheme is built to work regardless of evaluation order.
923The first time a unique expression is executed, the actual expression is evaluated and the accompanying boolean is set to true.
924Every subsequent evaluation of the unique expression then results in an access to the stored result of the actual expression.
925Tuple member expressions also take advantage of unique expressions in the case of possible impurity.
926
927Currently, the \CFA translator has a very broad, imprecise definition of impurity, where any function call is assumed to be impure.
928This 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.
929
930The various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions.
931A 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.
932The 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.
933However, 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.
934\end{comment}
935
936
937\section{Control Structures}
938
939
940\subsection{\texorpdfstring{Labelled \LstKeywordStyle{continue} / \LstKeywordStyle{break}}{Labelled continue / break}}
941
942While C provides @continue@ and @break@ statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
943Unfortunately, this restriction forces programmers to use @goto@ to achieve the equivalent control-flow for more than one level of nesting.
944To 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.
945For both @continue@ and @break@, the target label must be directly associated with a @for@, @while@ or @do@ statement;
946for @break@, the target label can also be associated with a @switch@, @if@ or compound (@{}@) statement.
947Figure~\ref{f:MultiLevelExit} shows @continue@ and @break@ indicating the specific control structure, and the corresponding C program using only @goto@ and labels.
948The innermost loop has 7 exit points, which cause continuation or termination of one or more of the 7 nested control-structures.
949
950\begin{figure}
951\lstDeleteShortInline@%
952\begin{tabular}{@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{\hspace{\parindentlnth}}l@{}}
953\multicolumn{1}{@{\hspace{\parindentlnth}}c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}   & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
954\begin{cfa}
955`LC:` {
956        ... $declarations$ ...
957        `LS:` switch ( ... ) {
958          case 3:
959                `LIF:` if ( ... ) {
960                        `LF:` for ( ... ) {
961                                `LW:` while ( ... ) {
962                                        ... break `LC`; ...
963                                        ... break `LS`; ...
964                                        ... break `LIF`; ...
965                                        ... continue `LF;` ...
966                                        ... break `LF`; ...
967                                        ... continue `LW`; ...
968                                        ... break `LW`; ...
969                                } // while
970                        } // for
971                } else {
972                        ... break `LIF`; ...
973                } // if
974        } // switch
975} // compound
976\end{cfa}
977&
978\begin{cfa}
979{
980        ... $declarations$ ...
981        switch ( ... ) {
982          case 3:
983                if ( ... ) {
984                        for ( ... ) {
985                                while ( ... ) {
986                                        ... goto `LC`; ...
987                                        ... goto `LS`; ...
988                                        ... goto `LIF`; ...
989                                        ... goto `LFC`; ...
990                                        ... goto `LFB`; ...
991                                        ... goto `LWC`; ...
992                                        ... goto `LWB`; ...
993                                  `LWC`: ; } `LWB:` ;
994                          `LFC:` ; } `LFB:` ;
995                } else {
996                        ... goto `LIF`; ...
997                } `L3:` ;
998        } `LS:` ;
999} `LC:` ;
1000\end{cfa}
1001&
1002\begin{cfa}
1003
1004
1005
1006
1007
1008
1009
1010// terminate compound
1011// terminate switch
1012// terminate if
1013// continue loop
1014// terminate loop
1015// continue loop
1016// terminate loop
1017
1018
1019
1020// terminate if
1021
1022
1023
1024\end{cfa}
1025\end{tabular}
1026\lstMakeShortInline@%
1027\caption{Multi-level Exit}
1028\label{f:MultiLevelExit}
1029\end{figure}
1030
1031Both labelled @continue@ and @break@ are a @goto@ restricted in the following ways:
1032\begin{itemize}
1033\item
1034They cannot create a loop, which means only the looping constructs cause looping.
1035This restriction means all situations resulting in repeated execution are clearly delineated.
1036\item
1037They cannot branch into a control structure.
1038This restriction prevents missing declarations and/or initializations at the start of a control structure resulting in undefined behaviour.
1039\end{itemize}
1040The 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.
1041Furthermore, 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.
1042With @goto@, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader.
1043Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs.
1044The implicit targets of the current @continue@ and @break@, \ie the closest enclosing loop or @switch@, change as certain constructs are added or removed.
1045
1046\TODO{choose and fallthrough here as well?}
1047
1048
1049\subsection{\texorpdfstring{\LstKeywordStyle{with} Clause / Statement}{with Clause / Statement}}
1050\label{s:WithClauseStatement}
1051
1052Grouping heterogenous 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:
1053\begin{cfa}
1054struct S {                                                                      $\C{// aggregate}$
1055        char c;                                                                 $\C{// fields}$
1056        int i;
1057        double d;
1058};
1059S s, as[10];
1060\end{cfa}
1061However, routines manipulating aggregates must repeat the aggregate name to access its containing fields:
1062\begin{cfa}
1063void f( S s ) {
1064        `s.`c; `s.`i; `s.`d;                                    $\C{// access containing fields}$
1065}
1066\end{cfa}
1067A similar situation occurs in object-oriented programming, \eg \CC:
1068\begin{C++}
1069class C {
1070        char c;                                                                 $\C{// fields}$
1071        int i;
1072        double d;
1073        int mem() {                                                             $\C{// implicit "this" parameter}$
1074                `this->`c; `this->`i; `this->`d;        $\C{// access containing fields}$
1075        }
1076}
1077\end{C++}
1078Nesting of member routines in a \lstinline[language=C++]@class@ allows eliding \lstinline[language=C++]@this->@ because of lexical scoping.
1079However, for other aggregate parameters, qualification is necessary:
1080\begin{cfa}
1081struct T { double m, n; };
1082int C::mem( T & t ) {                                           $\C{// multiple aggregate parameters}$
1083        c; i; d;                                                                $\C{\color{red}// this-\textgreater.c, this-\textgreater.i, this-\textgreater.d}$
1084        `t.`m; `t.`n;                                                   $\C{// must qualify}$
1085}
1086\end{cfa}
1087
1088% In object-oriented programming, there is an implicit first parameter, often names @self@ or @this@, which is elided.
1089% In any programming language, some functions have a naturally close relationship with a particular data type.
1090% Object-oriented programming allows this close relationship to be codified in the language by making such functions \newterm{class methods} of their related data type.
1091% Class methods have certain privileges with respect to their associated data type, notably un-prefixed access to the fields of that data type.
1092% When writing C functions in an object-oriented style, this un-prefixed access is swiftly missed, as access to fields of a @Foo* f@ requires an extra three characters @f->@ every time, which disrupts coding flow and clutters the produced code.
1093%
1094% \TODO{Fill out section. Be sure to mention arbitrary expressions in with-blocks, recent change driven by Thierry to prioritize field name over parameters.}
1095
1096To simplify the programmer experience, \CFA provides a @with@ clause/statement (see Pascal~\cite[\S~4.F]{Pascal}) to elide aggregate qualification to fields by opening a scope containing the field identifiers.
1097Hence, the qualified fields become variables with the side-effect that it is easier to optimizing field references in a block.
1098\begin{cfa}
1099void f( S s ) `with( s )` {                                     $\C{// with clause}$
1100        c; i; d;                                                                $\C{\color{red}// s.c, s.i, s.d}$
1101}
1102\end{cfa}
1103and the equivalence for object-style programming is:
1104\begin{cfa}
1105int mem( S & this ) `with( this )` {            $\C{// with clause}$
1106        c; i; d;                                                                $\C{\color{red}// this.c, this.i, this.d}$
1107}
1108\end{cfa}
1109with the generality of opening multiple aggregate-parameters:
1110\begin{cfa}
1111int mem( S & s, T & t ) `with( s, t )` {        $\C{// multiple aggregate parameters}$
1112        c; i; d;                                                                $\C{\color{red}// s.c, s.i, s.d}$
1113        m; n;                                                                   $\C{\color{red}// t.m, t.n}$
1114}
1115\end{cfa}
1116
1117In detail, the @with@ clause/statement has the form:
1118\begin{cfa}
1119$\emph{with-statement}$:
1120        'with' '(' $\emph{expression-list}$ ')' $\emph{compound-statement}$
1121\end{cfa}
1122and may appear as the body of a routine or nested within a routine body.
1123Each expression in the expression-list provides a type and object.
1124The type must be an aggregate type.
1125(Enumerations are already opened.)
1126The object is the implicit qualifier for the open structure-fields.
1127
1128All expressions in the expression list are open in ``parallel'' within the compound statement.
1129This semantic is different from Pascal, which nests the openings.
1130The difference between parallel and nesting occurs for fields with the same name but different type:
1131\begin{cfa}
1132struct S { int i; int j; double m; } s, w;
1133struct T { int i; int k; int m } t, w;
1134with( s, t ) {
1135        j + k;                                                                  $\C{// unambiguous, s.j + t.m}$
1136        m = 5.0;                                                                $\C{// unambiguous, t.m = 5.0}$
1137        m = 1;                                                                  $\C{// unambiguous, s.m = 1}$
1138        int a = s.i + m;                                                $\C{// unambiguous, a = s.i + t.i}$
1139        int b = s.i + t.i;                                              $\C{// unambiguous, qualification}$
1140        sout | (double)m | endl;                                $\C{// unambiguous, cast}$
1141        i;                                                                              $\C{// ambiguous}$
1142}
1143\end{cfa}
1144\CFA's ability to overload variables means usages of field with the same names can be automatically disambiguated, eliminating most qualification.
1145Qualification or a cast is used to disambiguate.
1146A cast may be necessary to disambiguate between the overload variables in a @with@ expression:
1147\begin{cfa}
1148with( w ) { ... }                                                       $\C{// ambiguous, same name and no context}$
1149with( (S)w ) { ... }                                            $\C{// unambiguous}$
1150\end{cfa}
1151
1152\begin{cfa}
1153struct S { int i, j; } sv;
1154with( sv ) {
1155        S & sr = sv;
1156        with( sr ) {
1157                S * sp = &sv;
1158                with( *sp ) {
1159                        i = 3; j = 4;                                   $\C{\color{red}// sp-{\textgreater}i, sp-{\textgreater}j}$
1160                }
1161                i = 3; j = 4;                                           $\C{\color{red}// sr.i, sr.j}$
1162        }
1163        i = 3; j = 4;                                                   $\C{\color{red}// sv.i, sv.j}$
1164}
1165\end{cfa}
1166
1167The statement form is used within a block:
1168\begin{cfa}
1169int foo() {
1170        struct S1 { ... } s1;
1171        struct S2 { ... } s2;
1172        `with( s1 )` {                                                  $\C{// with statement}$
1173                // access fields of s1 without qualification
1174                `with( s2 )` {                                          $\C{// nesting}$
1175                        // access fields of s1 and s2 without qualification
1176                }
1177        }
1178        `with( s1, s2 )` {
1179                // access unambiguous fields of s1 and s2 without qualification
1180        }
1181}
1182\end{cfa}
1183
1184
1185\subsection{Exception Handling ???}
1186
1187
1188\section{Declarations}
1189
1190It is important to the design team that \CFA subjectively ``feel like'' C to user programmers.
1191An important part of this subjective feel is maintaining C's procedural programming paradigm, as opposed to the object-oriented paradigm of other systems languages such as \CC and Rust.
1192Maintaining this procedural paradigm means that coding patterns that work in C will remain not only functional but idiomatic in \CFA, reducing the mental burden of retraining C programmers and switching between C and \CFA development.
1193Nonetheless, some features of object-oriented languages are undeniably convienient, and the \CFA design team has attempted to adapt them to a procedural paradigm so as to incorporate their benefits into \CFA; two of these features are resource management and name scoping.
1194
1195
1196\subsection{Alternative Declaration Syntax}
1197
1198\newcommand{\R}[1]{\Textbf{#1}}
1199\newcommand{\B}[1]{{\Textbf[blue]{#1}}}
1200\newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}}
1201
1202C declaration syntax is notoriously confusing and error prone.
1203For example, many C programmers are confused by a declaration as simple as:
1204\begin{cquote}
1205\lstDeleteShortInline@%
1206\begin{tabular}{@{}ll@{}}
1207\begin{cfa}
1208int * x[5]
1209\end{cfa}
1210&
1211\raisebox{-0.75\totalheight}{\input{Cdecl}}
1212\end{tabular}
1213\lstMakeShortInline@%
1214\end{cquote}
1215Is this an array of 5 pointers to integers or a pointer to an array of 5 integers?
1216If there is any doubt, it implies productivity and safety issues even for basic programs.
1217Another 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.
1218For example, a routine returning a pointer to an array of integers is defined and used in the following way:
1219\begin{cfa}
1220int `(*`f`())[`5`]` {...};                              $\C{// definition}$
1221 ... `(*`f`())[`3`]` += 1;                              $\C{// usage}$
1222\end{cfa}
1223Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
1224While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice.
1225
1226\CFA provides its own type, variable and routine declarations, using a different syntax.
1227The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right of the base type.
1228In the following example, \R{red} is the base type and \B{blue} is qualifiers.
1229The \CFA declarations move the qualifiers to the left of the base type, \ie move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type.
1230\begin{cquote}
1231\lstDeleteShortInline@%
1232\lstset{moredelim=**[is][\color{blue}]{+}{+}}
1233\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1234\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1235\begin{cfa}
1236+[5] *+ `int` x1;
1237+* [5]+ `int` x2;
1238+[* [5] int]+ f`( int p )`;
1239\end{cfa}
1240&
1241\begin{cfa}
1242`int` +*+ x1 +[5]+;
1243`int` +(*+x2+)[5]+;
1244+int (*+f`( int p )`+)[5]+;
1245\end{cfa}
1246\end{tabular}
1247\lstMakeShortInline@%
1248\end{cquote}
1249The only exception is bit field specification, which always appear to the right of the base type.
1250% 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.
1251However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list.
1252For instance, variables @x@ and @y@ of type pointer to integer are defined in \CFA as follows:
1253\begin{cquote}
1254\lstDeleteShortInline@%
1255\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1256\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1257\begin{cfa}
1258`*` int x, y;
1259\end{cfa}
1260&
1261\begin{cfa}
1262int `*`x, `*`y;
1263\end{cfa}
1264\end{tabular}
1265\lstMakeShortInline@%
1266\end{cquote}
1267The downside of this semantics is the need to separate regular and pointer declarations:
1268\begin{cquote}
1269\lstDeleteShortInline@%
1270\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1271\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1272\begin{cfa}
1273`*` int x;
1274int y;
1275\end{cfa}
1276&
1277\begin{cfa}
1278int `*`x, y;
1279
1280\end{cfa}
1281\end{tabular}
1282\lstMakeShortInline@%
1283\end{cquote}
1284which is prescribing a safety benefit.
1285Other examples are:
1286\begin{cquote}
1287\lstDeleteShortInline@%
1288\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1289\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
1290\begin{cfa}
1291[ 5 ] int z;
1292[ 5 ] * char w;
1293* [ 5 ] double v;
1294struct s {
1295        int f0:3;
1296        * int f1;
1297        [ 5 ] * int f2;
1298};
1299\end{cfa}
1300&
1301\begin{cfa}
1302int z[ 5 ];
1303char * w[ 5 ];
1304double (* v)[ 5 ];
1305struct s {
1306        int f0:3;
1307        int * f1;
1308        int * f2[ 5 ]
1309};
1310\end{cfa}
1311&
1312\begin{cfa}
1313// array of 5 integers
1314// array of 5 pointers to char
1315// pointer to array of 5 doubles
1316
1317// common bit field syntax
1318
1319
1320
1321\end{cfa}
1322\end{tabular}
1323\lstMakeShortInline@%
1324\end{cquote}
1325
1326All type qualifiers, \eg @const@, @volatile@, etc., are used in the normal way with the new declarations and also appear left to right, \eg:
1327\begin{cquote}
1328\lstDeleteShortInline@%
1329\begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}}
1330\multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\
1331\begin{cfa}
1332const * const int x;
1333const * [ 5 ] const int y;
1334\end{cfa}
1335&
1336\begin{cfa}
1337int const * const x;
1338const int (* const y)[ 5 ]
1339\end{cfa}
1340&
1341\begin{cfa}
1342// const pointer to const integer
1343// const pointer to array of 5 const integers
1344\end{cfa}
1345\end{tabular}
1346\lstMakeShortInline@%
1347\end{cquote}
1348All declaration qualifiers, \eg @extern@, @static@, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier}
1349The 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}} \eg:
1350\begin{cquote}
1351\lstDeleteShortInline@%
1352\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1353\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
1354\begin{cfa}
1355extern [ 5 ] int x;
1356static * const int y;
1357\end{cfa}
1358&
1359\begin{cfa}
1360int extern x[ 5 ];
1361const int static * y;
1362\end{cfa}
1363&
1364\begin{cfa}
1365// externally visible array of 5 integers
1366// internally visible pointer to constant int
1367\end{cfa}
1368\end{tabular}
1369\lstMakeShortInline@%
1370\end{cquote}
1371
1372The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine @sizeof@:
1373\begin{cquote}
1374\lstDeleteShortInline@%
1375\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1376\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1377\begin{cfa}
1378y = (* int)x;
1379i = sizeof([ 5 ] * int);
1380\end{cfa}
1381&
1382\begin{cfa}
1383y = (int *)x;
1384i = sizeof(int * [ 5 ]);
1385\end{cfa}
1386\end{tabular}
1387\lstMakeShortInline@%
1388\end{cquote}
1389
1390Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration.
1391Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
1392Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX-like systems.
1393
1394
1395\subsection{References}
1396
1397All variables in C have an \newterm{address}, a \newterm{value}, and a \newterm{type};
1398at 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.
1399The C type-system does not always track the relationship between a value and its address;
1400a 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'').
1401For 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.
1402Despite 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.
1403
1404Within a lexical scope, lvalue expressions have an \newterm{address interpretation} for writing a value or a \newterm{value interpretation} to read a value.
1405For example, in @x = y@, @x@ has an address interpretation, while @y@ has a value interpretation.
1406Though 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.
1407In C, for any type @T@ there is a pointer type @T *@, the value of which is the address of a value of type @T@.
1408A 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 @&?@.
1409
1410\begin{cfa}
1411int x = 1, y = 2, * p1, * p2, ** p3;
1412p1 = &x;                                                                $\C{// p1 points to x}$
1413p2 = &y;                                                                $\C{// p2 points to y}$
1414p3 = &p1;                                                               $\C{// p3 points to p1}$
1415*p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15);
1416\end{cfa}
1417
1418Unfortunately, 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.
1419For both brevity and clarity, it would be desirable to have the compiler figure out how to elide the dereference operators in a complex expression such as the assignment to @*p2@ above.
1420However, 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 user programmer may write one when they mean the other, and precluding any simple algorithm for elision of dereference operators.
1421To solve these problems, \CFA introduces reference types @T&@; a @T&@ has exactly the same value as a @T*@, but where the @T*@ takes the address interpretation by default, a @T&@ takes the value interpretation by default, as below:
1422
1423\begin{cfa}
1424int x = 1, y = 2, & r1, & r2, && r3;
1425&r1 = &x;  $\C{// r1 points to x}$
1426&r2 = &y;  $\C{// r2 points to y}$
1427&&r3 = &&r1;  $\C{// r3 points to r2}$
1428r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15);  $\C{// implicit dereferencing}$
1429\end{cfa}
1430
1431Except for auto-dereferencing by the compiler, this reference example is exactly the same as the previous pointer example.
1432Hence, 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.
1433One 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:
1434
1435\begin{cfa}
1436`*`r2 = ((`*`r1 + `*`r2) * (`**`r3 - `*`r1)) / (`**`r3 - 15);
1437\end{cfa}
1438
1439References in \CFA are similar to those in \CC, but with a couple important improvements, both of which can be seen in the example above.
1440Firstly, \CFA does not forbid references to references, unlike \CC.
1441This provides a much more orthogonal design for library implementors, obviating the need for workarounds such as @std::reference_wrapper@.
1442
1443Secondly, unlike the references in \CC which always point to a fixed address, \CFA references are rebindable.
1444This allows \CFA references to be default-initialized (\eg to a null pointer), and also to point to different addresses throughout their lifetime.
1445This rebinding is accomplished without adding any new syntax to \CFA, but simply by extending the existing semantics of the address-of operator in C.
1446
1447In 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.
1448In \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.
1449The 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.
1450This rebinding can occur to an arbitrary depth of reference nesting; loosely speaking, nested address-of operators will produce an lvalue nested pointer up to as deep as the reference they're applied to.
1451These 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@.
1452More precisely:
1453\begin{itemize}
1454        \item
1455        if @R@ is an rvalue of type {@T &@$_1 \cdots$@ &@$_r$} where $r \ge 1$ references (@&@ symbols) than @&R@ has type {@T `*`&@$_{\color{red}2} \cdots$@ &@$_{\color{red}r}$}, \\ \ie @T@ pointer with $r-1$ references (@&@ symbols).
1456       
1457        \item
1458        if @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).
1459\end{itemize}
1460Since 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 in user code can be made based solely on convenience.
1461
1462By analogy to pointers, \CFA references also allow cv-qualifiers such as @const@:
1463
1464\begin{cfa}
1465const int cx = 5;               $\C{// cannot change cx}$
1466const int & cr = cx;    $\C{// cannot change cr's referred value}$
1467&cr = &cx;                              $\C{// rebinding cr allowed}$
1468cr = 7;                                 $\C{// ERROR, cannot change cr}$
1469int & const rc = x;             $\C{// must be initialized, like in \CC}$
1470&rc = &x;                               $\C{// ERROR, cannot rebind rc}$
1471rc = 7;                                 $\C{// x now equal to 7}$
1472\end{cfa}
1473
1474Given that a reference is meant to represent a lvalue, \CFA provides some syntactic shortcuts when initializing references.
1475There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, and return/temporary binding.
1476In each of these contexts, the address-of operator on the target lvalue may (in fact, must) be elided.
1477The syntactic motivation for this 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@.
1478
1479More 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; this conversion can actually be used in any context in \CFA an implicit conversion would be allowed.
1480Similarly, 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.
1481The final reference conversion included in \CFA is ``rvalue-to-reference'' conversion, implemented by means of an implicit temporary.
1482When 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.
1483This 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.
1484\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.
1485
1486
1487\subsection{Constructors and Destructors}
1488
1489One of the strengths of C is the control over memory management it gives programmers, allowing resource release to be more consistent and precisely timed than is possible with garbage-collected memory management.
1490However, this manual approach to memory management is often verbose, and it is useful to manage resources other than memory (\eg file handles) using the same mechanism as memory.
1491\CC is well-known for an approach to manual memory management that addresses both these issues, Resource Aquisition Is Initialization (RAII), implemented by means of special \newterm{constructor} and \newterm{destructor} functions; we have implemented a similar feature in \CFA.
1492While RAII is a common feature of object-oriented programming languages, its inclusion in \CFA does not violate the design principle that \CFA retain the same procedural paradigm as C.
1493In particular, \CFA does not implement class-based encapsulation: neither the constructor nor any other function has privileged access to the implementation details of a type, except through the translation-unit-scope method of opaque structs provided by C.
1494
1495In \CFA, a constructor is a function named @?{}@, while a destructor is a function named @^?{}@; like other \CFA operators, these names represent the syntax used to call the constructor or destructor, \eg @x{ ... };@ or @^x{};@.
1496Every constructor and destructor must have a return type of @void@, and its first parameter must have a reference type whose base type is the type of the object the function constructs or destructs.
1497This first parameter is informally called the @this@ parameter, as in many object-oriented languages, though a programmer may give it an arbitrary name.
1498Destructors must have exactly one parameter, while constructors allow passing of zero or more additional arguments along with the @this@ parameter.
1499
1500\begin{cfa}
1501struct Array {
1502        int * data;
1503        int len;
1504};
1505
1506void ?{}( Array& arr ) {
1507        arr.len = 10;
1508        arr.data = calloc( arr.len, sizeof(int) );
1509}
1510
1511void ^?{}( Array& arr ) {
1512        free( arr.data );
1513}
1514
1515{
1516        Array x;
1517        `?{}(x);`       $\C{// implicitly compiler-generated}$
1518        // ... use x
1519        `^?{}(x);`      $\C{// implicitly compiler-generated}$
1520}
1521\end{cfa}
1522
1523In the example above, a \newterm{default constructor} (\ie one with no parameters besides the @this@ parameter) and destructor are defined for the @Array@ struct, a dynamic array of @int@.
1524@Array@ is an example of a \newterm{managed type} in \CFA, a type with a non-trivial constructor or destructor, or with a field of a managed type.
1525As in the example, all instances of managed types are implicitly constructed upon allocation, and destructed upon deallocation; this ensures proper initialization and cleanup of resources contained in managed types, in this case the @data@ array on the heap.
1526The exact details of the placement of these implicit constructor and destructor calls are omitted here for brevity, the interested reader should consult \cite{Schluntz17}.
1527
1528Constructor calls are intended to seamlessly integrate with existing C initialization syntax, providing a simple and familiar syntax to veteran C programmers and allowing constructor calls to be inserted into legacy C code with minimal code changes.
1529As such, \CFA also provides syntax for \newterm{copy initialization} and \newterm{initialization parameters}:
1530
1531\begin{cfa}
1532void ?{}( Array& arr, Array other );
1533
1534void ?{}( Array& arr, int size, int fill );
1535
1536Array y = { 20, 0xDEADBEEF }, z = y;
1537\end{cfa}
1538
1539Copy 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.
1540Other 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.
1541
1542In addition to initialization syntax, \CFA provides two ways to explicitly call constructors and destructors.
1543Explicit calls to constructors double as a placement syntax, useful for construction of member fields in user-defined constructors and reuse of large storage allocations.
1544While the existing function-call syntax works for explicit calls to constructors and destructors, \CFA also provides a more concise \newterm{operator syntax} for both:
1545
1546\begin{cfa}
1547Array a, b;
1548a{};                            $\C{// default construct}$
1549b{ a };                         $\C{// copy construct}$
1550^a{};                           $\C{// destruct}$
1551a{ 5, 0xFFFFFFFF };     $\C{// explicit constructor call}$
1552\end{cfa}
1553
1554To 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.
1555These default functions can be overridden by user-generated versions of them.
1556For 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.
1557For user-generated types, the four functions are also automatically generated.
1558@enum@ types are handled the same as their underlying integral type, and unions are also bitwise copied and no-op initialized and destructed.
1559For compatibility with C, a copy constructor from the first union member type is also defined.
1560For @struct@ types, each of the four functions are implicitly defined to call their corresponding functions on each member of the struct.
1561To better simulate the behaviour of C initializers, a set of \newterm{field constructors} is also generated for structures.
1562A 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.
1563To 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.
1564These semantics closely mirror the rule for implicit declaration of constructors in \CC\cite[p.~186]{ANSI98:C++}.
1565
1566In 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.
1567If 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.
1568Any C initializer can be the right-hand side of an \lstinline|@=| initializer, \eg  \lstinline|Array a @= { 0, 0x0 }|, with the usual C initialization semantics.
1569In 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.
1570
1571\subsection{Default Parameters}
1572
1573
1574\section{Literals}
1575
1576C 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 floating-point types are very similar, differing from each other only in suffix.
1577In 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.
1578
1579\subsection{0/1}
1580
1581In 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.
1582As 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.
1583The 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.
1584To 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.
1585With 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)@.
1586\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.
1587
1588\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.
1589The addition of @one_t@ allows generic algorithms to handle the unit value uniformly for types where that is meaningful.
1590\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.
1591
1592\subsection{Units}
1593
1594Alternative call syntax (literal argument before routine name) to convert basic literals into user literals.
1595
1596{\lstset{language=CFA,deletedelim=**[is][]{`}{`},moredelim=**[is][\color{red}]{@}{@}}
1597\begin{cfa}
1598struct Weight { double stones; };
1599
1600void ?{}( Weight & w ) { w.stones = 0; } $\C{// operations}$
1601void ?{}( Weight & w, double w ) { w.stones = w; }
1602Weight ?+?( Weight l, Weight r ) { return (Weight){ l.stones + r.stones }; }
1603
1604Weight @?`st@( double w ) { return (Weight){ w }; } $\C{// backquote for units}$
1605Weight @?`lb@( double w ) { return (Weight){ w / 14.0 }; }
1606Weight @?`kg@( double w ) { return (Weight) { w * 0.1575}; }
1607
1608int main() {
1609        Weight w, hw = { 14 };                  $\C{// 14 stone}$
1610        w = 11@`st@ + 1@`lb@;
1611        w = 70.3@`kg@;
1612        w = 155@`lb@;
1613        w = 0x_9b_u@`lb@;                               $\C{// hexadecimal unsigned weight (155)}$
1614        w = 0_233@`lb@;                                 $\C{// octal weight (155)}$
1615        w = 5@`st@ + 8@`kg@ + 25@`lb@ + hw;
1616}
1617\end{cfa}
1618}%
1619
1620\section{Evaluation}
1621\label{sec:eval}
1622
1623Though \CFA provides significant added functionality over C, these features have a low runtime penalty.
1624In fact, \CFA's features for generic programming can enable faster runtime execution than idiomatic @void *@-based C code.
1625This 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}).
1626Since 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.
1627A more illustrative benchmark measures the costs of idiomatic usage of each language's features.
1628Figure~\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}.
1629The benchmark test is similar for C and \CC.
1630The 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.
1631
1632\begin{figure}
1633\begin{lstlisting}[xleftmargin=3\parindentlnth,aboveskip=0pt,belowskip=0pt]
1634int main( int argc, char * argv[] ) {
1635        FILE * out = fopen( "cfa-out.txt", "w" );
1636        int maxi = 0, vali = 42;
1637        stack(int) si, ti;
1638
1639        REPEAT_TIMED( "push_int", N, push( &si, vali ); )
1640        TIMED( "copy_int", ti = si; )
1641        TIMED( "clear_int", clear( &si ); )
1642        REPEAT_TIMED( "pop_int", N,
1643                int xi = pop( &ti ); if ( xi > maxi ) { maxi = xi; } )
1644        REPEAT_TIMED( "print_int", N/2, print( out, vali, ":", vali, "\n" ); )
1645
1646        pair(_Bool, char) maxp = { (_Bool)0, '\0' }, valp = { (_Bool)1, 'a' };
1647        stack(pair(_Bool, char)) sp, tp;
1648
1649        REPEAT_TIMED( "push_pair", N, push( &sp, valp ); )
1650        TIMED( "copy_pair", tp = sp; )
1651        TIMED( "clear_pair", clear( &sp ); )
1652        REPEAT_TIMED( "pop_pair", N,
1653                pair(_Bool, char) xp = pop( &tp ); if ( xp > maxp ) { maxp = xp; } )
1654        REPEAT_TIMED( "print_pair", N/2, print( out, valp, ":", valp, "\n" ); )
1655        fclose(out);
1656}
1657\end{lstlisting}
1658\caption{\protect\CFA Benchmark Test}
1659\label{fig:BenchmarkTest}
1660\end{figure}
1661
1662The 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.
1663The \CCV variant illustrates an alternative object-oriented idiom where all objects inherit from a base @object@ class, mimicking a Java-like interface;
1664hence runtime checks are necessary to safely down-cast objects.
1665The 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.
1666For 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.
1667Note, the C benchmark uses unchecked casts as there is no runtime mechanism to perform such checks, while \CFA and \CC provide type-safety statically.
1668
1669Figure~\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.
1670The graph plots the median of 5 consecutive runs of each program, with an initial warm-up run omitted.
1671All code is compiled at \texttt{-O2} by GCC or G++ 6.2.0, with all \CC code compiled as \CCfourteen.
1672The 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.
1673
1674\begin{figure}
1675\centering
1676\input{timing}
1677\caption{Benchmark Timing Results (smaller is better)}
1678\label{fig:eval}
1679\end{figure}
1680
1681\begin{table}
1682\caption{Properties of benchmark code}
1683\label{tab:eval}
1684\newcommand{\CT}[1]{\multicolumn{1}{c}{#1}}
1685\begin{tabular}{rrrrr}
1686                                                                        & \CT{C}        & \CT{\CFA}     & \CT{\CC}      & \CT{\CCV}             \\ \hline
1687maximum memory usage (MB)                       & 10001         & 2502          & 2503          & 11253                 \\
1688source code size (lines)                        & 247           & 222           & 165           & 339                   \\
1689redundant type annotations (lines)      & 39            & 2                     & 2                     & 15                    \\
1690binary size (KB)                                        & 14            & 229           & 18            & 38                    \\
1691\end{tabular}
1692\end{table}
1693
1694The 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;
1695this inefficiency is exacerbated by the second level of generic types in the pair-based benchmarks.
1696By 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.
1697\CCV is slower than C largely due to the cost of runtime type-checking of down-casts (implemented with @dynamic_cast@);
1698There are two outliers in the graph for \CFA: all prints and pop of @pair@.
1699Both 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.
1700A compiler designed for \CFA could easily perform these optimizations.
1701Finally, the binary size for \CFA is larger because of static linking with the \CFA libraries.
1702
1703\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.
1704On 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.
1705\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;
1706with their omission, the \CCV line count is similar to C.
1707We 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.
1708
1709Raw line-count, however, is a fairly rough measure of code complexity;
1710another important factor is how much type information the programmer must manually specify, especially where that information is not checked by the compiler.
1711Such 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@).
1712To 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.
1713The \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.
1714The 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).
1715These uses are similar to the @new@ expressions in \CC, though the \CFA compiler's type resolver should shortly render even these type casts superfluous.
1716
1717
1718\section{Related Work}
1719
1720
1721\subsection{Polymorphism}
1722
1723\CC is the most similar language to \CFA;
1724both are extensions to C with source and runtime backwards compatibility.
1725The fundamental difference is in their engineering approach to C compatibility and programmer expectation.
1726While \CC provides good backwards compatibility with C, it has a steep learning curve for many of its extensions.
1727For example, polymorphism is provided via three disjoint mechanisms: overloading, inheritance, and templates.
1728The 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.
1729In 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.
1730The key mechanism to support separate compilation is \CFA's \emph{explicit} use of assumed properties for a type.
1731Until \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;
1732furthermore, \CC concepts are restricted to template polymorphism.
1733
1734Cyclone~\cite{Grossman06} also provides capabilities for polymorphic functions and existential types, similar to \CFA's @forall@ functions and generic types.
1735Cyclone 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.
1736Furthermore, 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@.
1737In \CFA terms, all Cyclone polymorphism must be dtype-static.
1738While 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.
1739Smith 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.
1740
1741Objective-C~\cite{obj-c-book} is an industrially successful extension to C.
1742However, Objective-C is a radical departure from C, using an object-oriented model with message-passing.
1743Objective-C did not support type-checked generics until recently \cite{xcode7}, historically using less-efficient runtime checking of object types.
1744The GObject~\cite{GObject} framework also adds object-oriented programming with runtime type-checking and reference-counting garbage-collection to C;
1745these features are more intrusive additions than those provided by \CFA, in addition to the runtime overhead of reference-counting.
1746Vala~\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.
1747Java~\cite{Java8} included generic types in Java~5, which are type-checked at compilation and type-erased at runtime, similar to \CFA's.
1748However, in Java, each object carries its own table of method pointers, while \CFA passes the method pointers separately to maintain a C-compatible layout.
1749Java is also a garbage-collected, object-oriented language, with the associated resource usage and C-interoperability burdens.
1750
1751D~\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.
1752However, 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.
1753D and Go are garbage-collected languages, imposing the associated runtime overhead.
1754The necessity of accounting for data transfer between managed runtimes and the unmanaged C runtime complicates foreign-function interfaces to C.
1755Furthermore, 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.
1756D 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.
1757Rust also possesses much more powerful abstraction capabilities for writing generic code than Go.
1758On 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.
1759\CFA, with its more modest safety features, allows direct ports of C code while maintaining the idiomatic style of the original source.
1760
1761
1762\subsection{Tuples/Variadics}
1763
1764Many programming languages have some form of tuple construct and/or variadic functions, \eg SETL, C, KW-C, \CC, D, Go, Java, ML, and Scala.
1765SETL~\cite{SETL} is a high-level mathematical programming language, with tuples being one of the primary data types.
1766Tuples in SETL allow subscripting, dynamic expansion, and multiple assignment.
1767C 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.
1768KW-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.
1769The main contributions of that work were adding MRVF, tuple mass and multiple assignment, and record-field access.
1770\CCeleven introduced @std::tuple@ as a library variadic template structure.
1771Tuples are a generalization of @std::pair@, in that they allow for arbitrary length, fixed-size aggregation of heterogeneous values.
1772Operations include @std::get<N>@ to extract values, @std::tie@ to create a tuple of references used for assignment, and lexicographic comparisons.
1773\CCseventeen proposes \emph{structured bindings}~\cite{Sutter15} to eliminate pre-declaring variables and use of @std::tie@ for binding the results.
1774This 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.
1775Furthermore, structured bindings are not a full replacement for @std::tie@, as it always declares new variables.
1776Like \CC, D provides tuples through a library variadic-template structure.
1777Go does not have tuples but supports MRVF.
1778Java'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.
1779Tuples are a fundamental abstraction in most functional programming languages, such as Standard ML~\cite{sml} and~\cite{Scala}, which decompose tuples using pattern matching.
1780
1781
1782\section{Conclusion and Future Work}
1783
1784The 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.
1785While 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.
1786The 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.
1787The contributions are a powerful type-system using parametric polymorphism and overloading, generic types, and tuples, which all have complex interactions.
1788The work is a challenging design, engineering, and implementation exercise.
1789On the surface, the project may appear as a rehash of similar mechanisms in \CC.
1790However, 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.
1791All of these new features are being used by the \CFA development-team to build the \CFA runtime-system.
1792Finally, we demonstrate that \CFA performance for some idiomatic cases is better than C and close to \CC, showing the design is practically applicable.
1793
1794There is ongoing work on a wide range of \CFA feature extensions, including arrays with size, exceptions, concurrent primitives, modules, and user-defined conversions.
1795(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.)
1796In addition, there are interesting future directions for the polymorphism design.
1797Notably, \CC template functions trade compile time and code bloat for optimal runtime of individual instantiations of polymorphic functions.
1798\CFA polymorphic functions use dynamic virtual-dispatch;
1799the 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.
1800Two 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).
1801These approaches are not mutually exclusive and allow performance optimizations to be applied only when necessary, without suffering global code-bloat.
1802In general, we believe separate compilation, producing smaller code, works well with loaded hardware-caches, which may offset the benefit of larger inlined-code.
1803
1804
1805\section{Acknowledgments}
1806
1807The 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.
1808%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.
1809% 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.
1810
1811
1812\bibliographystyle{plain}
1813\bibliography{pl}
1814
1815
1816\appendix
1817
1818\section{Benchmark Stack Implementation}
1819\label{sec:BenchmarkStackImplementation}
1820
1821\lstset{basicstyle=\linespread{0.9}\sf\small}
1822
1823Throughout, @/***/@ designates a counted redundant type annotation.
1824
1825\smallskip\noindent
1826\CFA
1827\begin{lstlisting}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
1828forall(otype T) struct stack_node {
1829        T value;
1830        stack_node(T) * next;
1831};
1832forall(otype T) void ?{}(stack(T) * s) { (&s->head){ 0 }; }
1833forall(otype T) void ?{}(stack(T) * s, stack(T) t) {
1834        stack_node(T) ** crnt = &s->head;
1835        for ( stack_node(T) * next = t.head; next; next = next->next ) {
1836                *crnt = ((stack_node(T) *)malloc()){ next->value }; /***/
1837                stack_node(T) * acrnt = *crnt;
1838                crnt = &acrnt->next;
1839        }
1840        *crnt = 0;
1841}
1842forall(otype T) stack(T) ?=?(stack(T) * s, stack(T) t) {
1843        if ( s->head == t.head ) return *s;
1844        clear(s);
1845        s{ t };
1846        return *s;
1847}
1848forall(otype T) void ^?{}(stack(T) * s) { clear(s); }
1849forall(otype T) _Bool empty(const stack(T) * s) { return s->head == 0; }
1850forall(otype T) void push(stack(T) * s, T value) {
1851        s->head = ((stack_node(T) *)malloc()){ value, s->head }; /***/
1852}
1853forall(otype T) T pop(stack(T) * s) {
1854        stack_node(T) * n = s->head;
1855        s->head = n->next;
1856        T x = n->value;
1857        ^n{};
1858        free(n);
1859        return x;
1860}
1861forall(otype T) void clear(stack(T) * s) {
1862        for ( stack_node(T) * next = s->head; next; ) {
1863                stack_node(T) * crnt = next;
1864                next = crnt->next;
1865                delete(crnt);
1866        }
1867        s->head = 0;
1868}
1869\end{lstlisting}
1870
1871\medskip\noindent
1872\CC
1873\begin{lstlisting}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
1874template<typename T> class stack {
1875        struct node {
1876                T value;
1877                node * next;
1878                node( const T & v, node * n = nullptr ) : value(v), next(n) {}
1879        };
1880        node * head;
1881        void copy(const stack<T>& o) {
1882                node ** crnt = &head;
1883                for ( node * next = o.head;; next; next = next->next ) {
1884                        *crnt = new node{ next->value }; /***/
1885                        crnt = &(*crnt)->next;
1886                }
1887                *crnt = nullptr;
1888        }
1889  public:
1890        stack() : head(nullptr) {}
1891        stack(const stack<T>& o) { copy(o); }
1892        stack(stack<T> && o) : head(o.head) { o.head = nullptr; }
1893        ~stack() { clear(); }
1894        stack & operator= (const stack<T>& o) {
1895                if ( this == &o ) return *this;
1896                clear();
1897                copy(o);
1898                return *this;
1899        }
1900        stack & operator= (stack<T> && o) {
1901                if ( this == &o ) return *this;
1902                head = o.head;
1903                o.head = nullptr;
1904                return *this;
1905        }
1906        bool empty() const { return head == nullptr; }
1907        void push(const T & value) { head = new node{ value, head };  /***/ }
1908        T pop() {
1909                node * n = head;
1910                head = n->next;
1911                T x = std::move(n->value);
1912                delete n;
1913                return x;
1914        }
1915        void clear() {
1916                for ( node * next = head; next; ) {
1917                        node * crnt = next;
1918                        next = crnt->next;
1919                        delete crnt;
1920                }
1921                head = nullptr;
1922        }
1923};
1924\end{lstlisting}
1925
1926\medskip\noindent
1927C
1928\begin{lstlisting}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
1929struct stack_node {
1930        void * value;
1931        struct stack_node * next;
1932};
1933struct stack new_stack() { return (struct stack){ NULL }; /***/ }
1934void copy_stack(struct stack * s, const struct stack * t, void * (*copy)(const void *)) {
1935        struct stack_node ** crnt = &s->head;
1936        for ( struct stack_node * next = t->head; next; next = next->next ) {
1937                *crnt = malloc(sizeof(struct stack_node)); /***/
1938                **crnt = (struct stack_node){ copy(next->value) }; /***/
1939                crnt = &(*crnt)->next;
1940        }
1941        *crnt = 0;
1942}
1943_Bool stack_empty(const struct stack * s) { return s->head == NULL; }
1944void push_stack(struct stack * s, void * value) {
1945        struct stack_node * n = malloc(sizeof(struct stack_node)); /***/
1946        *n = (struct stack_node){ value, s->head }; /***/
1947        s->head = n;
1948}
1949void * pop_stack(struct stack * s) {
1950        struct stack_node * n = s->head;
1951        s->head = n->next;
1952        void * x = n->value;
1953        free(n);
1954        return x;
1955}
1956void clear_stack(struct stack * s, void (*free_el)(void *)) {
1957        for ( struct stack_node * next = s->head; next; ) {
1958                struct stack_node * crnt = next;
1959                next = crnt->next;
1960                free_el(crnt->value);
1961                free(crnt);
1962        }
1963        s->head = NULL;
1964}
1965\end{lstlisting}
1966
1967\medskip\noindent
1968\CCV
1969\begin{lstlisting}[xleftmargin=2\parindentlnth,aboveskip=0pt,belowskip=0pt]
1970stack::node::node( const object & v, node * n ) : value( v.new_copy() ), next( n ) {}
1971void stack::copy(const stack & o) {
1972        node ** crnt = &head;
1973        for ( node * next = o.head; next; next = next->next ) {
1974                *crnt = new node{ *next->value };
1975                crnt = &(*crnt)->next;
1976        }
1977        *crnt = nullptr;
1978}
1979stack::stack() : head(nullptr) {}
1980stack::stack(const stack & o) { copy(o); }
1981stack::stack(stack && o) : head(o.head) { o.head = nullptr; }
1982stack::~stack() { clear(); }
1983stack & stack::operator= (const stack & o) {
1984        if ( this == &o ) return *this;
1985        clear();
1986        copy(o);
1987        return *this;
1988}
1989stack & stack::operator= (stack && o) {
1990        if ( this == &o ) return *this;
1991        head = o.head;
1992        o.head = nullptr;
1993        return *this;
1994}
1995bool stack::empty() const { return head == nullptr; }
1996void stack::push(const object & value) { head = new node{ value, head }; /***/ }
1997ptr<object> stack::pop() {
1998        node * n = head;
1999        head = n->next;
2000        ptr<object> x = std::move(n->value);
2001        delete n;
2002        return x;
2003}
2004void stack::clear() {
2005        for ( node * next = head; next; ) {
2006                node * crnt = next;
2007                next = crnt->next;
2008                delete crnt;
2009        }
2010        head = nullptr;
2011}
2012\end{lstlisting}
2013
2014
2015\begin{comment}
2016
2017\subsubsection{bench.h}
2018(\texttt{bench.hpp} is similar.)
2019
2020\lstinputlisting{evaluation/bench.h}
2021
2022\subsection{C}
2023
2024\subsubsection{c-stack.h} ~
2025
2026\lstinputlisting{evaluation/c-stack.h}
2027
2028\subsubsection{c-stack.c} ~
2029
2030\lstinputlisting{evaluation/c-stack.c}
2031
2032\subsubsection{c-pair.h} ~
2033
2034\lstinputlisting{evaluation/c-pair.h}
2035
2036\subsubsection{c-pair.c} ~
2037
2038\lstinputlisting{evaluation/c-pair.c}
2039
2040\subsubsection{c-print.h} ~
2041
2042\lstinputlisting{evaluation/c-print.h}
2043
2044\subsubsection{c-print.c} ~
2045
2046\lstinputlisting{evaluation/c-print.c}
2047
2048\subsubsection{c-bench.c} ~
2049
2050\lstinputlisting{evaluation/c-bench.c}
2051
2052\subsection{\CFA}
2053
2054\subsubsection{cfa-stack.h} ~
2055
2056\lstinputlisting{evaluation/cfa-stack.h}
2057
2058\subsubsection{cfa-stack.c} ~
2059
2060\lstinputlisting{evaluation/cfa-stack.c}
2061
2062\subsubsection{cfa-print.h} ~
2063
2064\lstinputlisting{evaluation/cfa-print.h}
2065
2066\subsubsection{cfa-print.c} ~
2067
2068\lstinputlisting{evaluation/cfa-print.c}
2069
2070\subsubsection{cfa-bench.c} ~
2071
2072\lstinputlisting{evaluation/cfa-bench.c}
2073
2074\subsection{\CC}
2075
2076\subsubsection{cpp-stack.hpp} ~
2077
2078\lstinputlisting[language=c++]{evaluation/cpp-stack.hpp}
2079
2080\subsubsection{cpp-print.hpp} ~
2081
2082\lstinputlisting[language=c++]{evaluation/cpp-print.hpp}
2083
2084\subsubsection{cpp-bench.cpp} ~
2085
2086\lstinputlisting[language=c++]{evaluation/cpp-bench.cpp}
2087
2088\subsection{\CCV}
2089
2090\subsubsection{object.hpp} ~
2091
2092\lstinputlisting[language=c++]{evaluation/object.hpp}
2093
2094\subsubsection{cpp-vstack.hpp} ~
2095
2096\lstinputlisting[language=c++]{evaluation/cpp-vstack.hpp}
2097
2098\subsubsection{cpp-vstack.cpp} ~
2099
2100\lstinputlisting[language=c++]{evaluation/cpp-vstack.cpp}
2101
2102\subsubsection{cpp-vprint.hpp} ~
2103
2104\lstinputlisting[language=c++]{evaluation/cpp-vprint.hpp}
2105
2106\subsubsection{cpp-vbench.cpp} ~
2107
2108\lstinputlisting[language=c++]{evaluation/cpp-vbench.cpp}
2109\end{comment}
2110
2111\end{document}
2112
2113% Local Variables: %
2114% tab-width: 4 %
2115% compile-command: "make" %
2116% End: %
Note: See TracBrowser for help on using the repository browser.