source: doc/papers/general/Paper.tex @ 493d73a

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

update library discussion

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