source: doc/papers/general/Paper.tex @ 636e1b9

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

changes and corrections to match SPE proofs

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