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

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

referee responses

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