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

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since b7c55277 was 4137e31, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

fix age of standardized

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