source: doc/papers/general/Paper.tex @ 49eb6a2

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

switch to SPE latex macros

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