source: doc/papers/general/Paper.tex @ 2097cd4

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

updates, change CFA evaluation code

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