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

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

relocate AMA paper macros

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