source: doc/papers/general/Paper.tex @ 3d8f2f8

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 3d8f2f8 was 3d8f2f8, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

more changes

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