% take off review (for line numbers) and anonymous (for anonymization) on submission
% \documentclass[format=acmlarge, anonymous, review]{acmart}
\documentclass[format=acmlarge,review]{acmart}

\usepackage{xspace,calc,comment}
\usepackage{upquote}									% switch curled `'" to straight
\usepackage{listings}									% format program code

\makeatletter
% parindent is relative, i.e., toggled on/off in environments like itemize, so store the value for
% use rather than use \parident directly.
\newlength{\parindentlnth}
\setlength{\parindentlnth}{\parindent}

\newlength{\gcolumnposn}				% temporary hack because lstlisting does handle tabs correctly
\newlength{\columnposn}
\setlength{\gcolumnposn}{2.75in}
\setlength{\columnposn}{\gcolumnposn}
\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@commentstyle{#2}}}
\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
\makeatother

% Useful macros
\newcommand{\CFA}{C$\mathbf\forall$\xspace} % Cforall symbolic name
\newcommand{\CC}{\rm C\kern-.1em\hbox{+\kern-.25em+}\xspace} % C++ symbolic name
\newcommand{\CCeleven}{\rm C\kern-.1em\hbox{+\kern-.25em+}11\xspace} % C++11 symbolic name
\newcommand{\CCfourteen}{\rm C\kern-.1em\hbox{+\kern-.25em+}14\xspace} % C++14 symbolic name
\newcommand{\CCseventeen}{\rm C\kern-.1em\hbox{+\kern-.25em+}17\xspace} % C++17 symbolic name
\newcommand{\CCtwenty}{\rm C\kern-.1em\hbox{+\kern-.25em+}20\xspace} % C++20 symbolic name

\newcommand{\TODO}{\textbf{TODO}}
\newcommand{\eg}{\textit{e}.\textit{g}.,\xspace}
\newcommand{\ie}{\textit{i}.\textit{e}.,\xspace}
\newcommand{\etc}{\textit{etc}.,\xspace}

% CFA programming language, based on ANSI C (with some gcc additions)
\lstdefinelanguage{CFA}[ANSI]{C}{
	morekeywords={_Alignas,_Alignof,__alignof,__alignof__,asm,__asm,__asm__,_At,_Atomic,__attribute,__attribute__,auto,
		_Bool,catch,catchResume,choose,_Complex,__complex,__complex__,__const,__const__,disable,dtype,enable,__extension__,
		fallthrough,fallthru,finally,forall,ftype,_Generic,_Imaginary,inline,__label__,lvalue,_Noreturn,one_t,otype,restrict,_Static_assert,
		_Thread_local,throw,throwResume,trait,try,ttype,typeof,__typeof,__typeof__,zero_t},
}%

\lstset{
language=CFA,
columns=fullflexible,
basicstyle=\linespread{0.9}\sf,							% reduce line spacing and use sanserif font
stringstyle=\tt,										% use typewriter font
tabsize=4,												% 4 space tabbing
xleftmargin=\parindent,									% indent code to paragraph indentation
%mathescape=true,										% LaTeX math escape in CFA code $...$
escapechar=\$,											% LaTeX escape in CFA code
%keepspaces=true,										%
showstringspaces=false,									% do not show spaces with cup
showlines=true,											% show blank lines at end of code
aboveskip=4pt,											% spacing above/below code block
belowskip=3pt,
% replace/adjust listing characters that look bad in sanserif
literate={-}{\raisebox{-0.15ex}{\texttt{-}}}1 {^}{\raisebox{0.6ex}{$\scriptscriptstyle\land\,$}}1
	{~}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}}1 {_}{\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}1 % {`}{\ttfamily\upshape\hspace*{-0.1ex}`}1
	{<-}{$\leftarrow$}2 {=>}{$\Rightarrow$}2,
moredelim=**[is][\color{red}]{`}{`},
}% lstset

% inline code @...@
\lstMakeShortInline@

% ACM Information
\citestyle{acmauthoryear}

\acmJournal{PACMPL}

\title{Generic and Tuple Types with Efficient Dynamic Layout in \CFA}

\author{Aaron Moss}
\email{a3moss@uwaterloo.ca}
\author{Robert Schluntz}
\email{rschlunt@uwaterloo.ca}
\author{Peter Buhr}
\email{pabuhr@uwaterloo.ca}
\affiliation{%
	\institution{University of Waterloo}
	\department{David R. Cheriton School of Computer Science}
	\streetaddress{Davis Centre, University of Waterloo}
	\city{Waterloo}
	\state{ON}
	\postcode{N2L 3G1}
	\country{Canada}
}

\terms{generic, tuple, types}
\keywords{generic types, tuple types, polymorphic functions, C, Cforall}

\begin{CCSXML}
<ccs2012>
<concept>
<concept_id>10011007.10011006.10011008.10011024.10011025</concept_id>
<concept_desc>Software and its engineering~Polymorphism</concept_desc>
<concept_significance>500</concept_significance>
</concept>
<concept>
<concept_id>10011007.10011006.10011008.10011024.10011028</concept_id>
<concept_desc>Software and its engineering~Data types and structures</concept_desc>
<concept_significance>500</concept_significance>
</concept>
<concept>
<concept_id>10011007.10011006.10011041.10011047</concept_id>
<concept_desc>Software and its engineering~Source code generation</concept_desc>
<concept_significance>300</concept_significance>
</concept>
</ccs2012>
\end{CCSXML}

\ccsdesc[500]{Software and its engineering~Polymorphism}
\ccsdesc[500]{Software and its engineering~Data types and structures}
\ccsdesc[300]{Software and its engineering~Source code generation}

\begin{abstract}
The 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. This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more. Nonetheless, C, first standardized over thirty years ago, lacks many features that make programming in more modern languages safer and more productive. The 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. Prior 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. Specifically, \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 engineers. This paper describes only two \CFA extensions, generic and tuple types, and how they are implemented in accordance with these principles.
\end{abstract}

\begin{document}
\maketitle


\section{Introduction \& Background}

\CFA\footnote{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. Four key design goals were set out in the original design of \CFA~\citep{Bilson03}:
\begin{enumerate}
\item The behaviour of standard C code must remain the same when translated by a \CFA compiler as when translated by a C compiler.
\item Standard C code must be as fast and as small when translated by a \CFA compiler as when translated by a C compiler.
\item \CFA code must be at least as portable as standard C code.
\item Extensions introduced by \CFA must be translated in the most efficient way possible.
\end{enumerate}
The purpose of these goals is to ensure that existing C code-bases can be converted to \CFA incrementally and with minimal effort, and that programmers who know C can productively generate \CFA code without training beyond the features they wish to employ. In its current implementation, \CFA is compiled by translating it to the GCC-dialect of C~\citep{GCCExtensions}, allowing it to leverage the portability and code optimizations provided by GCC, meeting goals (1)-(3).

\CFA has been previously extended with polymorphic functions and name overloading (including operator overloading) by \citet{Bilson03}, and deterministically-executed constructors and destructors by \citet{Schluntz17}. This paper describes how generic and tuple types are designed and implemented in \CFA in accordance with both the backward compatibility goals and existing features described above.


\subsection{Polymorphic Functions}
\label{sec:poly-fns}

\CFA's polymorphism was originally formalized by \citet{Ditchfield92}, and first implemented by \citet{Bilson03}. The signature feature of \CFA is parametric-polymorphic functions; such functions are written using a @forall@ clause (which gives the language its name):
\begin{lstlisting}
`forall( otype T )` T identity( T val ) { return val; }
int forty_two = identity( 42 );				$\C{// T is bound to int, forty\_two == 42}$
\end{lstlisting}
The @identity@ function above can be applied to any complete object-type (or ``@otype@''). The type variable @T@ is transformed into a set of additional implicit parameters to @identity@ that encode sufficient information about @T@ to create and return a variable of that type. The \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. If this extra information is not needed, e.g., for a pointer, the type parameter can be declared as @dtype T@, where @dtype@ is short for ``data type''.

Here, the runtime cost of polymorphism is spread over each polymorphic call, due to passing more arguments to polymorphic functions; preliminary experiments have shown this overhead to be similar to \CC virtual function calls. An advantage of this design is that, unlike \CC template functions, \CFA @forall@ functions are compatible with C separate compilation.

Since bare polymorphic-types provide only a narrow set of available operations, \CFA provides a \emph{type assertion} mechanism to provide further type information, where type assertions may be variable or function declarations that depend on a polymorphic type variable. For instance, @twice@ can be defined using the \CFA syntax for operator overloading:
\begin{lstlisting}
forall( otype T | { T `?`+`?`(T, T); } )	$\C{// ? denotes operands}$
  T twice( T x ) { return x + x; }			$\C{// (2)}$
int val = twice( twice( 3.7 ) );
\end{lstlisting}
which works for any type @T@ with an addition operator defined. The translator accomplishes this polymorphism by creating a wrapper function for calling @+@ with @T@ bound to @double@, then providing this function to the first call of @twice@. It then has the option of using the same @twice@ again 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 in its type analysis. The first approach has a late conversion from integer to floating-point on the final assignment, while the second has an eager conversion to integer. \CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach.

Monomorphic specializations of polymorphic functions can satisfy polymorphic type-assertions.
% \begin{lstlisting}
% forall(otype T `| { T twice(T); }`)		$\C{// type assertion}$
% T four_times(T x) { return twice( twice(x) ); }
% double twice(double d) { return d * 2.0; }	$\C{// (1)}$
% double magic = four_times(10.5); 			$\C{// T bound to double, uses (1) to satisfy type assertion}$
% \end{lstlisting}
\begin{lstlisting}
forall( otype T `| { int ?<?( T, T ); }` )	$\C{// type assertion}$
  void qsort( const T * arr, size_t dimension );
forall( otype T `| { int ?<?( T, T ); }` )	$\C{// type assertion}$
  T * bsearch( T key, const T * arr, size_t dimension );
double vals[10] = { /* 10 floating-point values */ };
qsort( vals, 10 );							$\C{// sort array}$
double * val = bsearch( 5.0, vals, 10 );	$\C{// binary search sorted array for key}$
\end{lstlisting}
@qsort@ and @bsearch@ can only be called with arguments for which there exists a function named @<@ taking two arguments of the same type and returning an @int@ value.
Here, the built-in monomorphic specialization of @<@ for type @double@ is passed as an additional implicit parameter to the calls of @qsort@ and @bsearch@.

Crucial to the design of a new programming language are the libraries to access thousands of external features.
\CFA inherits a massive compatible library-base, where other programming languages have to rewrite or provide fragile inter-language communication with C.
A simple example is leveraging the existing type-unsafe C @bsearch@:
\begin{lstlisting}
void * bsearch( const void * key, const void * base, size_t nmemb, size_t size,
                     int (* compar)(const void *, const void *));
int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 :
					 *(double *)t2 < *(double *)t1 ? 1 : 0; }
double key = ...;
double *v = (double *)bsearch( &key, vals, size, sizeof( vals[0] ), comp );
\end{lstlisting}
but providing a type-safe \CFA overloaded wrapper.
\begin{lstlisting}
forall( otype T | { int ?<?( T, T ); } )
  T * bsearch( T key, const T * arr, size_t dimension ) {
	int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ }
	return (T *)bsearch( &key, arr, dimension, sizeof(T), comp );
}
forall( otype T | { int ?<?( T, T ); } )
  unsigned int bsearch( T key, const T * arr, size_t dimension ) {
	T *result = bsearch( key, arr, dimension );	$\C{// call first version}$
	return result ? result - arr : dimension;	$\C{// pointer subtraction includes sizeof(T)}$
}
double * val = bsearch( 5.0, vals, 10 );		$\C{// selection based on return type}$
int posn = bsearch( 5.0, vals, 10 );
\end{lstlisting}
The nested routine @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
As well, an alternate kind of return is made available, position versus pointer to found element.
\CC's type-system cannot disambiguate between the two versions of @bsearch@ because it does not use the return type in overload resolution, nor can \CC separately compile a templated @bsearch@.

Call-site inferencing and nested functions provide a localized form of inheritance. For example, @qsort@ only sorts in ascending order using @<@. However, it is trivial to locally change this behaviour:
\begin{lstlisting}
{
	int ?<?( double x, double y ) { return x `>` y; }	$\C{// override behaviour}$
	qsort( vals, size );					$\C{// descending sort}$
}
\end{lstlisting}
Within the block, the nested version of @<@ performs @>@ and this local version overrides the built-in @<@ so it is passed to @qsort@.
Hence, programmers can easily form new local environments to maximize reuse of existing functions and types.

Finally, variables can also be overloaded:

\begin{lstlisting}
short int MAX = ...;
int MAX = ...;
double MAX = ...;
\end{lstlisting}
\begin{lstlisting}
short int s = MAX;  // select correct MAX
int i = MAX;
double d = MAX;
\end{lstlisting}


\subsection{Traits}

\CFA provides \emph{traits} to name a group of type assertions:
% \begin{lstlisting}
% trait has_magnitude(otype T) {
%     _Bool ?<?(T, T);						$\C{// comparison operator for T}$
%     T -?(T);								$\C{// negation operator for T}$
%     void ?{}(T*, zero_t);					$\C{// constructor from 0 literal}$
% };
% forall(otype M | has_magnitude(M))
% M abs( M m ) {
%     M zero = { 0 };							$\C{// uses zero\_t constructor from trait}$
%     return m < zero ? -m : m;
% }
% forall(otype M | has_magnitude(M))
% M max_magnitude( M a, M b ) {
%     return abs(a) < abs(b) ? b : a;
% }
% \end{lstlisting}
\begin{lstlisting}
trait summable( otype T ) {
	void ?{}(T*, zero_t);					$\C{// constructor from 0 literal}$
	T ?+?( T, T );							$\C{// assortment of additions}$
	T ?+=?( T *, T );
	T ++?( T * );
	T ?++( T * );
};
forall( otype T | summable( T ) )
  T sum( T a[$\,$], size_t dimension ) {
	T total = { 0 };							$\C{// instantiate T from 0}$
	for ( unsigned int i = 0; i < dimension; i += 1 )
		total += a[i];						$\C{// select appropriate +}$
	return total;
}
\end{lstlisting}
The trait name allows specifying the same set of assertions in multiple locations, preventing repetition mistakes at each function declaration.

In fact, the set of operators is incomplete, \eg no assignment, but @otype@ is syntactic sugar for the following implicit trait:
\begin{lstlisting}
trait otype( dtype T | sized(T) ) {
	// sized is a compiler-provided pseudo-trait for types with known size and alignment}
	void ?{}( T * );						$\C{// default constructor}$
	void ?{}( T *, T );						$\C{// copy constructor}$
	void ?=?( T *, T );						$\C{// assignment operator}$
	void ^?{}( T * );						$\C{// destructor}$
};
\end{lstlisting}
Given the information provided for an @otype@, variables of polymorphic type can be treated as if they were a complete struct type -- they can be stack-allocated using the @alloca@ compiler builtin, default or copy-initialized, assigned, and deleted. As an example, the @sum@ function produces generated code something like the following (simplified for clarity and brevity) \TODO{} fix example, maybe elide, it's likely too long with the more complicated function:
\begin{lstlisting}
void abs( size_t _sizeof_M, size_t _alignof_M,
		void (*_ctor_M)(void*), void (*_copy_M)(void*, void*),
		void (*_assign_M)(void*, void*), void (*_dtor_M)(void*),
		_Bool (*_lt_M)(void*, void*), void (*_neg_M)(void*, void*),
    	void (*_ctor_M_zero)(void*, int),
		void* m, void* _rtn ) {				$\C{// polymorphic parameter and return passed as void*}$
											$\C{// M zero = { 0 };}$
	void* zero = alloca(_sizeof_M);			$\C{// stack allocate zero temporary}$
	_ctor_M_zero(zero, 0);					$\C{// initialize using zero\_t constructor}$
											$\C{// return m < zero ? -m : m;}$
	void *_tmp = alloca(_sizeof_M);
	_copy_M( _rtn,							$\C{// copy-initialize return value}$
		_lt_M( m, zero ) ?					$\C{// check condition}$
		 (_neg_M(m, _tmp), _tmp) :			$\C{// negate m}$
		 m);
	_dtor_M(_tmp); _dtor_M(zero);			$\C{// destroy temporaries}$
}
\end{lstlisting}

Semantically, traits are simply a named lists of type assertions, but they may be used for many of the same purposes that interfaces in Java or abstract base classes in \CC are used for. Unlike Java interfaces or \CC base classes, \CFA types do not explicitly state any inheritance relationship to traits they satisfy; this can be considered a form of structural inheritance, similar to implementation of an interface in Go, as opposed to the nominal inheritance model of Java and \CC. Nominal inheritance can be simulated with traits using marker variables or functions:
\begin{lstlisting}
trait nominal(otype T) {
    T is_nominal;
};

int is_nominal;								$\C{// int now satisfies the nominal trait}$
\end{lstlisting}

Traits, however, are significantly more powerful than nominal-inheritance interfaces; most notably, traits may be used to declare a relationship among multiple types, a property that may be difficult or impossible to represent in nominal-inheritance type systems:
\begin{lstlisting}
trait pointer_like(otype Ptr, otype El) {
    lvalue El *?(Ptr);						$\C{// Ptr can be dereferenced into a modifiable value of type El}$
}

struct list {
    int value;
    list *next;								$\C{// may omit "struct" on type names}$
};

typedef list *list_iterator;

lvalue int *?( list_iterator it ) { return it->value; }
\end{lstlisting}

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@).
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.

\section{Generic Types}

One of the known shortcomings of standard C is that it does not provide reusable type-safe abstractions for generic data structures and algorithms. Broadly speaking, there are three approaches to create data structures in C. One approach is to write bespoke data structures for each context in which they are needed. While 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. A second approach is to use @void*@-based polymorphism. This approach is taken by the C standard library functions @qsort@ and @bsearch@, and does allow the use of common code for common functionality. However, basing all polymorphism on @void*@ eliminates the type-checker's ability to ensure that argument types are properly matched, often requires a number of extra function parameters, and also adds pointer indirection and dynamic allocation to algorithms and data structures that would not otherwise require them. A third approach to generic code is to use pre-processor macros to generate it -- this approach does allow the generated code to be both generic and type-checked, though any errors produced may be difficult to interpret. Furthermore, writing and invoking C code as preprocessor macros is unnatural and somewhat inflexible.

Other C-like languages such as \CC and Java use \emph{generic types} to produce type-safe abstract data types. The authors have chosen to implement generic types as well, with some care taken that the generic types design for \CFA integrates efficiently and naturally with the existing polymorphic functions in \CFA while retaining backwards compatibility with C; maintaining separate compilation is a particularly important constraint on the design. However, where the concrete parameters of the generic type are known, there is not extra overhead for the use of a generic type.

A 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:
\begin{lstlisting}
forall(otype R, otype S) struct pair {
    R first;
    S second;
};

forall(otype T)
T value( pair(const char*, T) p ) { return p.second; }

forall(dtype F, otype T)
T value_p( pair(F*, T*) p ) { return *p.second; }

pair(const char*, int) p = { "magic", 42 };
int magic = value( p );

pair(void*, int*) q = { 0, &p.second };
magic = value_p( q );
double d = 1.0;
pair(double*, double*) r = { &d, &d };
d = value_p( r );
\end{lstlisting}

\CFA classifies generic types as either \emph{concrete} or \emph{dynamic}. Dynamic generic types vary in their in-memory layout depending on their type parameters, while concrete generic types have a fixed memory layout regardless of type parameters. A type may have polymorphic parameters but still be concrete; in \CFA such types are called \emph{dtype-static}. Polymorphic pointers are an example of dtype-static types -- @forall(dtype T) T*@ is a polymorphic type, but for any @T@ chosen, @T*@ has exactly the same in-memory representation as a @void*@, and can therefore be represented by a @void*@ in code generation.

\CFA generic types may also specify constraints on their argument type to be checked by the compiler. For example, consider the following declaration of a sorted set type, which ensures that the set key supports comparison and tests for equality:
\begin{lstlisting}
forall(otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); })
struct sorted_set;
\end{lstlisting}

\subsection{Concrete Generic Types}

The \CFA translator instantiates concrete generic types by template-expanding them to fresh struct types; concrete generic types can therefore be used with zero runtime overhead. To enable inter-operation among equivalent instantiations of a generic type, the translator saves the set of instantiations currently in scope and reuses the generated struct declarations where appropriate. For example, a function declaration that accepts or returns a concrete generic type produces a declaration for the instantiated struct in the same scope, which all callers that can see that declaration may reuse. As an example of the expansion, the concrete instantiation for @pair(const char*, int)@ looks like this:
\begin{lstlisting}
struct _pair_conc1 {
	const char* first;
	int second;
};
\end{lstlisting}

A concrete generic type with dtype-static parameters is also expanded to a struct type, but this struct type is used for all matching instantiations. In the example above, the @pair(F*, T*)@ parameter to @value_p@ is such a type; its expansion looks something like this, and is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate:
\begin{lstlisting}
struct _pair_conc0 {
	void* first;
	void* second;
};
\end{lstlisting}

\subsection{Dynamic Generic Types}

Though \CFA implements concrete generic types efficiently, it also has a fully general system for computing with dynamic generic types. As 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. Dynamic generic structs have the same size and alignment parameter, and also an \emph{offset array} which contains the offsets of each member of the struct\footnote{Dynamic generic unions need no such offset array, as all members are at offset 0; the size and alignment parameters are still provided for dynamic unions, however.}. Access to members\footnote{The \lstinline@offsetof@ macro is implemented similarly.} of a dynamic generic struct is provided by adding the corresponding member of the offset array to the struct pointer at runtime, essentially moving a compile-time offset calculation to runtime where necessary.

These offset arrays are statically generated where possible. If a dynamic generic type is declared to be passed or returned by value from a polymorphic function, the translator can safely assume that the generic type is complete (that is, has a known layout) at any call-site, and the offset array is passed from the caller; if 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. As an example, @p.second@ in the @value@ function above is implemented as @*(p + _offsetof_pair[1])@, where @p@ is a @void*@, and @_offsetof_pair@ is the offset array passed in to @value@ for @pair(const char*, T)@. The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) };@.

In some cases the offset arrays cannot be statically generated. For instance, modularity is generally provided in C by including an opaque forward-declaration of a struct and associated accessor and mutator routines in a header file, with the actual implementations in a separately-compiled \texttt{.c} file. \CFA supports this pattern for generic types, and in this instance the caller does not know the actual layout or size of the dynamic generic type, and only holds it by pointer. The \CFA translator automatically generates \emph{layout functions} for cases where the size, alignment, and offset array of a generic struct cannot be passed in to a function from that function's caller. These 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 struct (un-@sized@ parameters are forbidden from the language from being used in a context that affects layout). Results of these layout functions are cached so that they are only computed once per type per function.%, as in the example below for @pair@.
% \begin{lstlisting}
% static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair,
% 		size_t _szeof_R, size_t _alignof_R, size_t _szeof_S, size_t _alignof_S) {
%     *_szeof_pair = 0; // default values
%     *_alignof_pair = 1;

% 	// add offset, size, and alignment of first field
%     _offsetof_pair[0] = *_szeof_pair;
%     *_szeof_pair += _szeof_R;
%     if ( *_alignof_pair < _alignof_R ) *_alignof_pair = _alignof_R;

% 	// padding, offset, size, and alignment of second field
%     if ( *_szeof_pair & (_alignof_S - 1) )
% 		*_szeof_pair += (_alignof_S - ( *_szeof_pair & (_alignof_S - 1) ) );
%     _offsetof_pair[1] = *_szeof_pair;
%     *_szeof_pair += _szeof_S;
%     if ( *_alignof_pair < _alignof_S ) *_alignof_pair = _alignof_S;

% 	// pad to struct alignment
%     if ( *_szeof_pair & (*_alignof_pair - 1) )
% 		*_szeof_pair += ( *_alignof_pair - ( *_szeof_pair & (*_alignof_pair - 1) ) );
% }
% \end{lstlisting}

Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature. For instance, a function that strips duplicate values from an unsorted @vector(T)@ would likely have a pointer to the vector as its only explicit parameter, but use some sort of @set(T)@ internally to test for duplicate values. This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function.

Whether a type is concrete, dtype-static, or dynamic is decided based solely on the type parameters and @forall@ clause on the struct declaration. This design allows opaque forward declarations of generic types like @forall(otype T) struct Box;@ -- like in C, all uses of @Box(T)@ can be in a separately compiled translation unit, and callers from other translation units know the proper calling conventions to use. If the definition of a struct type was included in the decision of 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.

\subsection{Applications}
\label{sec:generic-apps}

The reuse of dtype-static struct instantiations enables some useful programming patterns at zero runtime cost. The most important such pattern is using @forall(dtype T) T*@ as a type-checked replacement for @void*@, as in this example, which takes a @qsort@ or @bsearch@-compatible comparison routine and creates a similar lexicographic comparison for pairs of pointers:
\begin{lstlisting}
forall(dtype T)
int lexcmp( pair(T*, T*)* a, pair(T*, T*)* b, int (*cmp)(T*, T*) ) {
	int c = cmp(a->first, b->first);
	if ( c == 0 ) c = cmp(a->second, b->second);
	return c;
}
\end{lstlisting}
Since @pair(T*, T*)@ is a concrete type, there are no added implicit parameters to @lexcmp@, so the code generated by \CFA is effectively identical to a version of this function written in standard C using @void*@, yet the \CFA version is type-checked to ensure that the fields of both pairs and the arguments to the comparison function match in type.

Another useful pattern enabled by reused dtype-static type instantiations is zero-cost ``tag'' structs. Sometimes a particular bit of information is only useful for type-checking, and can be omitted at runtime. Tag structs can be used to provide this information to the compiler without further runtime overhead, as in the following example:
\begin{lstlisting}
forall(dtype Unit) struct scalar { unsigned long value; };

struct metres {};
struct litres {};

forall(dtype U)
scalar(U) ?+?(scalar(U) a, scalar(U) b) {
	return (scalar(U)){ a.value + b.value };
}

scalar(metres) half_marathon = { 21093 };
scalar(litres) swimming_pool = { 2500000 };

scalar(metres) marathon = half_marathon + half_marathon;
scalar(litres) two_pools = swimming_pool + swimming_pool;
marathon + swimming_pool; // ERROR -- caught by compiler
\end{lstlisting}
@scalar@ is a dtype-static type, so all uses of it use a single struct definition, containing only a single @unsigned long@, and can share the same implementations of common routines like @?+?@ -- these implementations may even be separately compiled, unlike \CC template functions. However, the \CFA type-checker ensures that matching types are used by all calls to @?+?@, preventing nonsensical computations like adding the length of a marathon to the volume of an olympic pool.

\section{Tuples}
\label{sec:tuples}

The @pair(R, S)@ generic type used as an example in the previous section can be considered a special case of a more general \emph{tuple} data structure. The authors have implemented tuples in \CFA, with a design particularly motivated by two use cases: \emph{multiple-return-value functions} and \emph{variadic functions}.

In standard C, functions can return at most one value. This restriction results in code that emulates functions with multiple return values by \emph{aggregation} or by \emph{aliasing}. In the former situation, the function designer creates a record type that combines all of the return values into a single type. Unfortunately, the designer must come up with a name for the return type and for each of its fields. Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model. As such, this technique is effective when used sparingly, but can quickly get out of hand if many functions need to return different combinations of types. In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters. The pointer parameters are assigned inside of the routine body to emulate a return. Using this approach, the caller is directly responsible for allocating storage for the additional temporary return values. This responsibility complicates the call site with a sequence of variable declarations leading up to the call. Also, while a disciplined use of @const@ can give clues about whether a pointer parameter is going to be used as an out parameter, it is not immediately obvious from only the routine signature whether the callee expects such a parameter to be initialized before the call. Furthermore, while many C routines that accept pointers are designed so that it is safe to pass @NULL@ as a parameter, there are many C routines that are not null-safe. On a related note, C does not provide a standard mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler.

C does provide a mechanism for variadic functions through manipulation of @va_list@ objects, but it is notoriously type-unsafe. A variadic function is one that contains at least one parameter, followed by @...@ as the last token in the parameter list. In particular, some form of \emph{argument descriptor} is needed to inform the function of the number of arguments and their types, commonly a format string or counter parameter. It is important to note that both of these mechanisms are inherently redundant, because they require the user to specify information that the compiler knows explicitly. This required repetition is error prone, because it is easy for the user to add or remove arguments without updating the argument descriptor. In addition, C requires the programmer to hard code all of the possible expected types. As a result, it is cumbersome to write a variadic function that is open to extension. For example, consider a simple function that sums $N$ @int@s:
\begin{lstlisting}
int sum(int N, ...) {
  va_list args;
  va_start(args, N);  // must manually specify last non-variadic argument
  int ret = 0;
  while(N) {
    ret += va_arg(args, int);  // must specify type
    N--;
  }
  va_end(args);
  return ret;
}

sum(3, 10, 20, 30);  // must keep initial counter argument in sync
\end{lstlisting}

The @va_list@ type is a special C data type that abstracts variadic argument manipulation. The @va_start@ macro initializes a @va_list@, given the last named parameter. Each use of the @va_arg@ macro allows access to the next variadic argument, given a type. Since the function signature does not provide any information on what types can be passed to a variadic function, the compiler does not perform any error checks on a variadic call. As such, it is possible to pass any value to the @sum@ function, including pointers, floating-point numbers, and structures. In the case where the provided type is not compatible with the argument's actual type after default argument promotions, or if too many arguments are accessed, the behaviour is undefined~\citep{C11}. Furthermore, there is no way to perform the necessary error checks in the @sum@ function at run-time, since type information is not carried into the function body. Since they rely on programmer convention rather than compile-time checks, variadic functions are inherently unsafe.

In practice, compilers can provide warnings to help mitigate some of the problems. For example, GCC provides the @format@ attribute to specify that a function uses a format string, which allows the compiler to perform some checks related to the standard format specifiers. Unfortunately, this attribute does not permit extensions to the format string syntax, so a programmer cannot extend it to warn for mismatches with custom types.

\subsection{Tuple Expressions}

The tuple extensions in \CFA can express multiple return values and variadic function parameters in an efficient and type-safe manner. \CFA introduces \emph{tuple expressions} and \emph{tuple types}. A tuple expression is an expression producing a fixed-size, ordered list of values of heterogeneous types. The type of a tuple expression is the tuple of the subexpression types, or a \emph{tuple type}. In \CFA, a tuple expression is denoted by a comma-separated list of expressions enclosed in square brackets. For example, the expression @[5, 'x', 10.5]@ has type @[int, char, double]@. The previous expression has three \emph{components}. Each component in a tuple expression can be any \CFA expression, including another tuple expression. The order of evaluation of the components in a tuple expression is unspecified, to allow a compiler the greatest flexibility for program optimization. It is, however, guaranteed that each component of a tuple expression is evaluated for side-effects, even if the result is not used. Multiple-return-value functions can equivalently be called \emph{tuple-returning functions}.

\CFA allows declaration of \emph{tuple variables}, variables of tuple type. For example:
\begin{lstlisting}
[int, char] most_frequent(const char*);

const char* str = "hello, world!";
[int, char] freq = most_frequent(str);
printf("%s -- %d %c\n", str, freq);
\end{lstlisting}
In this example, the type of the @freq@ and the return type of @most_frequent@ are both tuple types. Also of note is how the tuple expression @freq@ is implicitly flattened into separate @int@ and @char@ arguments to @printf@; this code snippet could have been shortened by replacing the last two lines with @printf("%s -- %d %c\n", str, most_frequent(str));@ using exactly the same mechanism.

In addition to variables of tuple type, it is also possible to have pointers to tuples, and arrays of tuples. Tuple types can be composed of any types, except for array types, since arrays are not of fixed size, which makes tuple assignment difficult when a tuple contains an array.
\begin{lstlisting}
[double, int] di;
[double, int] * pdi
[double, int] adi[10];
\end{lstlisting}
This example declares a variable of type @[double, int]@, a variable of type pointer to @[double, int]@, and an array of ten @[double, int]@.

\subsection{Flattening and Restructuring}

In function call contexts, tuples support implicit flattening and restructuring conversions. Tuple flattening recursively expands a tuple into the list of its basic components. Tuple structuring packages a list of expressions into a value of tuple type.
\begin{lstlisting}
int f(int, int);
int g([int, int]);
int h(int, [int, int]);
[int, int] x;
int y;

f(x);      // flatten
g(y, 10);  // structure
h(x, y);   // flatten & structure
\end{lstlisting}
In \CFA, each of these calls is valid. In the call to @f@, @x@ is implicitly flattened so that the components of @x@ are passed as the two arguments to @f@. For the call to @g@, the values @y@ and @10@ are structured into a single argument of type @[int, int]@ to match the type of the parameter of @g@. Finally, in the call to @h@, @y@ 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]@. The flexible structure of tuples permits a simple and expressive function call syntax to work seamlessly with both single- and multiple-return-value functions, and with any number of arguments of arbitrarily complex structure.

In {K-W C}~\citep{Buhr94a,Till89}, a precursor to \CFA, there were 4 tuple coercions: opening, closing, flattening, and structuring. Opening coerces a tuple value into a tuple of values, while closing converts a tuple of values into a single tuple value. Flattening coerces a nested tuple into a flat tuple, \ie it takes a tuple with tuple components and expands it into a tuple with only non-tuple components. Structuring moves in the opposite direction, \ie it takes a flat tuple value and provides structure by introducing nested tuple components.

In \CFA, the design has been simplified to require only the two conversions previously described, which trigger only in function call and return situations. Specifically, the expression resolution algorithm examines all of the possible alternatives for an expression to determine the best match. In resolving a function call expression, each combination of function value and list of argument alternatives is examined. Given a particular argument list and function value, the list of argument alternatives is flattened to produce a list of non-tuple valued expressions. Then the flattened list of expressions is compared with each value in the function's parameter list. If the parameter's type is not a tuple type, then the current argument value is unified with the parameter type, and on success the next argument and parameter are examined. If the parameter's type is a tuple type, then the structuring conversion takes effect, recursively applying the parameter matching algorithm using the tuple's component types as the parameter list types. Assuming a successful unification, eventually the algorithm gets to the end of the tuple type, which causes all of the matching expressions to be consumed and structured into a tuple expression. For example, in
\begin{lstlisting}
int f(int, [double, int]);
f([5, 10.2], 4);
\end{lstlisting}
There is only a single definition of @f@, and 3 arguments with only single interpretations. First, the argument alternative list @[5, 10.2], 4@ is flattened to produce the argument list @5, 10.2, 4@. Next, the parameter matching algorithm begins, with $P =~$@int@ and $A =~$@int@, which unifies exactly. Moving to the next parameter and argument, $P =~$@[double, int]@ and $A =~$@double@. This time, the parameter is a tuple type, so the algorithm applies recursively with $P' =~$@double@ and $A =~$@double@, which unifies exactly. Then $P' =~$@int@ and $A =~$@double@, which again unifies exactly. At this point, the end of $P'$ has been reached, so the arguments @10.2, 4@ are structured into the tuple expression @[10.2, 4]@. Finally, the end of the parameter list $P$ has also been reached, so the final expression is @f(5, [10.2, 4])@.

\subsection{Member Access}

At times, it is desirable to access a single component of a tuple-valued expression without creating unnecessary temporary variables to assign to. Given a tuple-valued expression @e@ and a compile-time constant integer $i$ where $0 \leq i < n$, where $n$ is the number of components in @e@, @e.i@ accesses the $i$\textsuperscript{th} component of @e@. For example,
\begin{lstlisting}
[int, double] x;
[char *, int] f();
void g(double, int);
[int, double] * p;

int y = x.0;  // access int component of x
y = f().1;  // access int component of f
p->0 = 5;  // access int component of tuple pointed-to by p
g(x.1, x.0);  // rearrange x to pass to g
double z = [x, f()].0.1;  // access second component of first component of tuple expression
\end{lstlisting}
As seen above, tuple-index expressions can occur on any tuple-typed expression, including tuple-returning functions, square-bracketed tuple expressions, and other tuple-index expressions, provided the retrieved component is also a tuple. This feature was proposed for {K-W C}, but never implemented~\citep[p.~45]{Till89}.

It is possible to access multiple fields from a single expression using a \emph{member-access tuple expression}. The result is a single tuple expression whose type is the tuple of the types of the members. For example,
\begin{lstlisting}
struct S { int x; double y; char * z; } s;
s.[x, y, z];
\end{lstlisting}
Here, the type of @s.[x, y, z]@ is @[int, double, char *]@. A member tuple expression has the form @a.[x, y, z];@ where @a@ is an expression with type @T@, where @T@ supports member access expressions, and @x, y, z@ are all members of @T@ with types @T$_x$@, @T$_y$@, and @T$_z$@ respectively. Then the type of @a.[x, y, z]@ is @[T$_x$, T$_y$, T$_z$]@.

Since 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 components, drop components, duplicate components, etc.):
\begin{lstlisting}
[int, int, long, double] x;
void f(double, long);

f(x.[0, 3]);          // f(x.0, x.3)
x.[0, 1] = x.[1, 0];  // [x.0, x.1] = [x.1, x.0]
[long, int, long] y = x.[2, 0, 2];
\end{lstlisting}

It is possible for a member tuple expression to contain other member access expressions:
\begin{lstlisting}
struct A { double i; int j; };
struct B { int * k; short l; };
struct C { int x; A y; B z; } v;
v.[x, y.[i, j], z.k];
\end{lstlisting}
This expression is equivalent to @[v.x, [v.y.i, v.y.j], v.z.k]@. That is, the aggregate expression is effectively distributed across the tuple, which allows simple and easy access to multiple components in an aggregate, without repetition. It is guaranteed that the aggregate expression to the left of the @.@ in a member tuple expression is evaluated exactly once. As such, it is safe to use member tuple expressions on the result of a side-effecting function.

\subsection{Tuple Assignment}

In addition to tuple-index expressions, individual components of tuples can be accessed by a \emph{destructuring assignment} which has a tuple expression with lvalue components on its left-hand side. More generally, an assignment where the left-hand side of the assignment operator has a tuple type is called \emph{tuple assignment}. There are two kinds of tuple assignment depending on whether the right-hand side of the assignment operator has a tuple type or a non-tuple type, called \emph{multiple assignment} and \emph{mass assignment}, respectively.
\begin{lstlisting}
int x;
double y;
[int, double] z;
[y, x] = 3.14;  // mass assignment
[x, y] = z;     // multiple assignment
z = 10;         // mass assignment
z = [x, y];     // multiple assignment
\end{lstlisting}
Let $L_i$ for $i$ in $[0, n)$ represent each component of the flattened left-hand side, $R_i$ represent each component of the flattened right-hand side of a multiple assignment, and $R$ represent the right-hand side of a mass assignment.

For a multiple assignment to be valid, both tuples must have the same number of elements when flattened. Multiple assignment assigns $R_i$ to $L_i$ for each $i$.
That is, @?=?(&$L_i$, $R_i$)@ must be a well-typed expression. In the previous example, @[x, y] = z@, @z@ is flattened into @z.0, z.1@, and the assignments @x = z.0@ and @y = z.1@ are executed.

A mass assignment assigns the value $R$ to each $L_i$. For a mass assignment to be valid, @?=?(&$L_i$, $R$)@ must be a well-typed expression. This rule differs from C cascading assignment (\eg @a=b=c@) in that conversions are applied to $R$ in each individual assignment, which prevents data loss from the chain of conversions that can happen during a cascading assignment. For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, which results in the value @3.14@ in @y@ and the value @3@ in @x@. On the other hand, the C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, which results in the value @3@ in @x@, and as a result the value @3@ in @y@ as well.

Both kinds of tuple assignment have parallel semantics, such that each value on the left side and right side is evaluated \emph{before} any assignments occur. As a result, it is possible to swap the values in two variables without explicitly creating any temporary variables or calling a function:
\begin{lstlisting}
int x = 10, y = 20;
[x, y] = [y, x];
\end{lstlisting}
After executing this code, @x@ has the value @20@ and @y@ has the value @10@.

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. This definition allows cascading tuple assignment and use of tuple assignment in other expression contexts, an occasionally useful idiom to keep code succinct and reduce repetition.
% In \CFA, tuple assignment is an expression where the result type is the type of the left-hand side of the assignment, as in normal assignment. That is, a tuple assignment produces the value of the left-hand side after assignment. These semantics allow cascading tuple assignment to work out naturally in any context where a tuple is permitted. These semantics are a change from the original tuple design in {K-W C}~\citep{Till89}, wherein tuple assignment was a statement that allows cascading assignments as a special case. This decision was made in an attempt to fix what was seen as a problem with assignment, wherein it can be used in many different locations, such as in function-call argument position. While permitting assignment as an expression does introduce the potential for subtle complexities, it is impossible to remove assignment expressions from \CFA without affecting backwards compatibility with C. Furthermore, there are situations where permitting assignment as an expression improves readability by keeping code succinct and reducing repetition, and complicating the definition of tuple assignment puts a greater cognitive burden on the user. In another language, tuple assignment as a statement could be reasonable, but it would be inconsistent for tuple assignment to be the only kind of assignment in \CFA that is not an expression.

\subsection{Casting}

In C, the cast operator is used to explicitly convert between types. In \CFA, the cast operator has a secondary use as type ascription. That 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:
\begin{lstlisting}
int f();     // (1)
double f();  // (2)

f();       // ambiguous - (1),(2) both equally viable
(int)f();  // choose (2)
\end{lstlisting}

Since casting is a fundamental operation in \CFA, casts should be given a meaningful interpretation in the context of tuples. Taking a look at standard C provides some guidance with respect to the way casts should work with tuples:
\begin{lstlisting}
int f();
void g();

(void)f();  // (1)
(int)g();  // (2)
\end{lstlisting}
In C, (1) is a valid cast, which calls @f@ and discards its result. On the other hand, (2) is invalid, because @g@ does not produce a result, so requesting an @int@ to materialize from nothing is nonsensical. Generalizing 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.

Formally, 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$. Excess 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. This approach follows naturally from the way that a cast to @void@ works in C.

For example, in
\begin{lstlisting}
  [int, int, int] f();
  [int, [int, int], int] g();

  ([int, double])f();           // (1)
  ([int, int, int])g();         // (2)
  ([void, [int, int]])g();      // (3)
  ([int, int, int, int])g();    // (4)
  ([int, [int, int, int]])g();  // (5)
\end{lstlisting}

(1) discards the last element of the return value and converts the second element to @double@. Since @int@ is effectively a 1-element tuple, (2) discards the second component of the second element of the return value of @g@. If @g@ is free of side effects, this expression is equivalent to @[(int)(g().0), (int)(g().1.0), (int)(g().2)]@.
Since @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)]@).

Note that a cast is not a function call in \CFA, so flattening and structuring conversions do not occur for cast expressions\footnote{User-defined conversions have been considered, but for compatibility with C and the existing use of casts as type ascription, any future design for such conversions would require more precise matching of types than allowed for function arguments and parameters.}. As such, (4) is invalid because the cast target type contains 4 components, while the source type contains only 3. Similarly, (5) is invalid because the cast @([int, int, int])(g().1)@ is invalid. That is, it is invalid to cast @[int, int]@ to @[int, int, int]@.

\subsection{Polymorphism}

Tuples also integrate with \CFA polymorphism as a special sort of generic type. Due to the implicit flattening and structuring conversions involved in argument passing, @otype@ and @dtype@ parameters are restricted to matching only with non-tuple types.
\begin{lstlisting}
forall(otype T, dtype U)
void f(T x, U * y);

f([5, "hello"]);
\end{lstlisting}
In this example, @[5, "hello"]@ is flattened, so that the argument list appears as @5, "hello"@. The argument matching algorithm binds @T@ to @int@ and @U@ to @const char*@, and calls the function as normal.

Tuples, however, may contain polymorphic components. For example, a plus operator can be written to add two triples of a type together.
\begin{lstlisting}
forall(otype T | { T ?+?(T, T); })
[T, T, T] ?+?([T, T, T] x, [T, T, T] y) {
  return [x.0+y.0, x.1+y.1, x.2+y.2];
}
[int, int, int] x;
int i1, i2, i3;
[i1, i2, i3] = x + ([10, 20, 30]);
\end{lstlisting}

Flattening and restructuring conversions are also applied to tuple types in polymorphic type assertions. Previously in \CFA, it has been assumed that assertion arguments must match the parameter type exactly, modulo polymorphic specialization (\ie no implicit conversions are applied to assertion arguments). In the example below:
\begin{lstlisting}
int f([int, double], double);
forall(otype T, otype U | { T f(T, U, U); })
void g(T, U);
g(5, 10.21);
\end{lstlisting}
If assertion arguments must match exactly, then the call to @g@ cannot be resolved, since the expected type of @f@ is flat, while the only @f@ in scope requires a tuple type. Since tuples are fluid, this requirement reduces the usability of tuples in polymorphic code. To ease this pain point, function parameter and return lists are flattened for the purposes of type unification, which allows the previous example to pass expression resolution.

This relaxation is made possible by extending the existing thunk generation scheme, as described by \citet{Bilson03}. Now, 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:
\begin{lstlisting}
int _thunk(int _p0, double _p1, double _p2) {
  return f([_p0, _p1], _p2);
}
\end{lstlisting}
Essentially, this thunk provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism. These thunks take advantage of GCC C nested functions to produce closures that have the usual function pointer signature.

\subsection{Variadic Tuples}

To define variadic functions, \CFA adds a new kind of type parameter, @ttype@. Matching against a @ttype@ (``tuple type'') parameter consumes all remaining argument components and packages them into a tuple, binding to the resulting tuple of types. In a given parameter list, there should be at most one @ttype@ parameter that must occur last, otherwise the call can never resolve, given the previous rule. This idea essentially matches normal variadic semantics, with a strong feeling of similarity to \CCeleven variadic templates. As such, @ttype@ variables are also referred to as \emph{argument} or \emph{parameter packs} in this paper.

Like variadic templates, the main way to manipulate @ttype@ polymorphic functions is through recursion. Since nothing is known about a parameter pack by default, assertion parameters are key to doing anything meaningful. Unlike variadic templates, @ttype@ polymorphic functions can be separately compiled.

For example, the C @sum@ function at the beginning of Section~\ref{sec:tuples} could be written using @ttype@ as:
\begin{lstlisting}
int sum(){ return 0; }        // (0)
forall(ttype Params | { int sum(Params); })
int sum(int x, Params rest) { // (1)
  return x+sum(rest);
}
sum(10, 20, 30);
\end{lstlisting}
Since (0) does not accept any arguments, it is not a valid candidate function for the call @sum(10, 20, 30)@.
In order to call (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]@.
In order to finish the resolution of @sum@, an assertion parameter that matches @int sum(int, int)@ is required.
Like in the previous iteration, (0) is not a valid candidate, so (1) is examined with @Params@ bound to @[int]@, requiring the assertion @int sum(int)@.
Next, (0) fails, and to satisfy (1) @Params@ is bound to @[]@, requiring an assertion @int sum()@.
Finally, (0) matches and (1) fails, which terminates the recursion.
Effectively, 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))@.

As a point of note, this version does not require any form of argument descriptor, since the \CFA type system keeps track of all of these details. It might be reasonable to take the @sum@ function a step further to enforce a minimum number of arguments:
\begin{lstlisting}
int sum(int x, int y){
  return x+y;
}
forall(ttype Params | { int sum(int, Params); })
int sum(int x, int y, Params rest) {
  return sum(x+y, rest);
}
\end{lstlisting}

One more iteration permits the summation of any summable type, as long as all arguments are the same type:
\begin{lstlisting}
trait summable(otype T) {
  T ?+?(T, T);
};
forall(otype R | summable(R))
R sum(R x, R y){
  return x+y;
}
forall(otype R, ttype Params
  | summable(R)
  | { R sum(R, Params); })
R sum(R x, R y, Params rest) {
  return sum(x+y, rest);
}
\end{lstlisting}
Unlike C, it is not necessary to hard code the expected type. This code is naturally open to extension, in that any user-defined type with a @?+?@ operator is automatically able to be used with the @sum@ function. That is to say, the programmer who writes @sum@ does not need full program knowledge of every possible data type, unlike what is necessary to write an equivalent function using the standard C mechanisms. Summing arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators.

It is also possible to write a type-safe variadic print routine which can replace @printf@:
\begin{lstlisting}
struct S { int x, y; };
forall(otype T, ttype Params |
  { void print(T); void print(Params); })
void print(T arg, Params rest) {
  print(arg);
  print(rest);
}
void print(char * x) { printf("%s", x); }
void print(int x) { printf("%d", x);  }
void print(S s) { print("{ ", s.x, ",", s.y, " }"); }

print("s = ", (S){ 1, 2 }, "\n");
\end{lstlisting}
This example routine showcases a variadic-template-like decomposition of the provided argument list. The individual @print@ routines allow printing a single element of a type. The polymorphic @print@ allows printing any list of types, as long as each individual type has a @print@ function. The individual print functions can be used to build up more complicated @print@ routines, such as for @S@, which is something that cannot be done with @printf@ in C.

It is also possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions. For example, it is possible to write @new@ as a library function:
\begin{lstlisting}
struct Pair(otype R, otype S);
forall(otype R, otype S)
void ?{}(Pair(R, S) *, R, S);  // (1)

forall(dtype T, ttype Params | sized(T) | { void ?{}(T *, Params); })
T * new(Params p) {
  return ((T*)malloc( sizeof(T) )){ p }; // construct into result of malloc
}

Pair(int, char) * x = new(42, '!');
\end{lstlisting}
The @new@ function provides the combination of type-safe @malloc@ with a constructor call, so that it becomes impossible to forget to construct dynamically allocated objects. This function provides the type-safety of @new@ in \CC, without the need to specify the allocated type again, thanks to return-type inference.

In the call to @new@, @Pair(double, char)@ is selected to match @T@, and @Params@ is expanded to match @[double, char]@. The constructor (1) may be specialized to  satisfy the assertion for a constructor with an interface compatible with @void ?{}(Pair(int, char) *, int, char)@.

\TODO{} Check if we actually can use ttype parameters on generic types (if they set the complete flag, it should work, or nearly so).

\subsection{Implementation}

Tuples are implemented in the \CFA translator via a transformation into generic types. For each $N$, the first time an $N$-tuple is seen in a scope a generic type with $N$ type parameters is generated. For example:
\begin{lstlisting}
[int, int] f() {
  [double, double] x;
  [int, double, int] y;
}
\end{lstlisting}
Is transformed into:
\begin{lstlisting}
forall(dtype T0, dtype T1 | sized(T0) | sized(T1))
struct _tuple2 {  // generated before the first 2-tuple
  T0 field_0;
  T1 field_1;
};
_tuple2(int, int) f() {
  _tuple2(double, double) x;
  forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2))
  struct _tuple3 {  // generated before the first 3-tuple
    T0 field_0;
    T1 field_1;
    T2 field_2;
  };
  _tuple3_(int, double, int) y;
}
\end{lstlisting}

Tuple expressions are then simply converted directly into compound literals:
\begin{lstlisting}
[5, 'x', 1.24];
\end{lstlisting}
Becomes:
\begin{lstlisting}
(_tuple3(int, char, double)){ 5, 'x', 1.24 };
\end{lstlisting}

Since tuples are essentially structures, tuple indexing expressions are just field accesses:
\begin{lstlisting}
void f(int, [double, char]);
[int, double] x;

x.0+x.1;
printf("%d %g\n", x);
f(x, 'z');
\end{lstlisting}
Is transformed into:
\begin{lstlisting}
void f(int, _tuple2(double, char));
_tuple2(int, double) x;

x.field_0+x.field_1;
printf("%d %g\n", x.field_0, x.field_1);
f(x.field_0, (_tuple2){ x.field_1, 'z' });
\end{lstlisting}
Note that due to flattening, @x@ used in the argument position is converted into the list of its fields. In the call to @f@, the second and third argument components are structured into a tuple argument. Similarly, tuple member expressions are recursively expanded into a list of member access expressions.

Expressions that may contain side effects are made into \emph{unique expressions} before being expanded by the flattening conversion. Each unique expression is assigned an identifier and is guaranteed to be executed exactly once:
\begin{lstlisting}
void g(int, double);
[int, double] h();
g(h());
\end{lstlisting}
Internally, this expression is converted to two variables and an expression:
\begin{lstlisting}
void g(int, double);
[int, double] h();

_Bool _unq0_finished_ = 0;
[int, double] _unq0;
g(
  (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).0,
  (_unq0_finished_ ? _unq0 : (_unq0 = f(), _unq0_finished_ = 1, _unq0)).1,
);
\end{lstlisting}
Since argument evaluation order is not specified by the C programming language, this scheme is built to work regardless of evaluation order. The first time a unique expression is executed, the actual expression is evaluated and the accompanying boolean is set to true. Every subsequent evaluation of the unique expression then results in an access to the stored result of the actual expression. Tuple member expressions also take advantage of unique expressions in the case of possible impurity.

Currently, the \CFA translator has a very broad, imprecise definition of impurity, where any function call is assumed to be impure. This 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.

The various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions. A 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. The 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. However, 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.

\section{Related Work}

\CC is the existing language it is most natural to compare \CFA to, as they are both more modern extensions to C with backwards source compatibility. The most fundamental difference in approach between \CC and \CFA is their approach to this C compatibility. \CC does provide fairly strong source backwards compatibility with C, but is a dramatically more complex language than C, and imposes a steep learning curve to use many of its extension features. For instance, in a break from general C practice, template code is typically written in header files, with a variety of subtle restrictions implied on its use by this choice, while the other polymorphism mechanism made available by \CC, class inheritance, requires programmers to learn an entirely new object-oriented programming paradigm; the interaction between templates and inheritance is also quite complex. \CFA, by contrast, has a single facility for polymorphic code, one which supports separate compilation and the existing procedural paradigm of C code. A major difference between the approaches of \CC and \CFA to polymorphism is that the set of assumed properties for a type is \emph{explicit} in \CFA. One of the major limiting factors of \CC's approach is that templates cannot be separately compiled, and, until concepts~\citep{C++Concepts} are standardized (currently anticipated for \CCtwenty), \CC provides no way to specify the requirements of a generic function in code beyond compilation errors for template expansion failures. By contrast, the explicit nature of assertions in \CFA allows polymorphic functions to be separately compiled, and for their requirements to be checked by the compiler; similarly, \CFA generic types may be opaque, unlike \CC template classes.

Cyclone also provides capabilities for polymorphic functions and existential types~\citep{Grossman06}, similar in concept to \CFA's @forall@ functions and generic types. Cyclone 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. Furthermore, Cyclone's polymorphic functions and types are restricted in that they may only abstract over types with the same layout and calling convention as @void*@, in practice only pointer types and @int@ - in \CFA terms, all Cyclone polymorphism must be dtype-static. This design provides the efficiency benefits discussed in Section~\ref{sec:generic-apps} for dtype-static polymorphism, but is more restrictive than \CFA's more general model.

Go and Rust are both modern, compiled languages with abstraction features similar to \CFA traits, \emph{interfaces} in Go and \emph{traits} in Rust. However, both languages represent dramatic departures from C in terms of language model, and neither has the same level of compatibility with C as \CFA. Go is a garbage-collected language, imposing the associated runtime overhead, and complicating foreign-function calls with the necessity of accounting for data transfer between the managed Go runtime and the unmanaged C runtime. Furthermore, 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. Rust is not garbage-collected, and thus has a lighter-weight runtime that is more easily interoperable with C. It also possesses much more powerful abstraction capabilities for writing generic code than Go. On the other hand, Rust's borrow-checker, while it does provide strong safety guarantees, is complex and difficult to learn, and imposes a distinctly idiomatic programming style on Rust. \CFA, with its more modest safety features, is significantly easier to port C code to, while maintaining the idiomatic style of the original source.

\section{Conclusion \& Future Work}

In conclusion, the authors' design for generic types and tuples imposes minimal runtime overhead while still supporting a full range of C features, including separately-compiled modules. There is ongoing work on a wide range of \CFA feature extensions, including reference types, exceptions, and concurrent programming primitives. In addition to this work, there are some interesting future directions the polymorphism design could take. Notably, \CC template functions trade compile time and code bloat for optimal runtime of individual instantiations of polymorphic functions. \CFA polymorphic functions, by contrast, use an approach that is essentially dynamic virtual dispatch. The runtime overhead of this approach is low, but not as low as \CC template functions, and it may be beneficial to provide a mechanism for particularly performance-sensitive code to close this gap. Further research is needed, but two promising approaches are to allow an annotation on polymorphic function call sites that tells the translator to create a template-specialization of the function (provided the code is visible in the current translation unit) or placing an annotation on polymorphic function definitions that instantiates a version of the polymorphic function specialized to some set of types. These approaches are not mutually exclusive, and would allow these performance optimizations to be applied only where most useful to increase performance, without suffering the code bloat or loss of generality of a template expansion approach where it is unnecessary.

\begin{acks}
This work is supported in part by a corporate partnership with \grantsponsor{Huawei}{Huawei Ltd.}{http://www.huawei.com}\ and 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.
\end{acks}

\bibliographystyle{ACM-Reference-Format}
\bibliography{cfa}

\end{document}

% Local Variables: %
% tab-width: 4 %
% compile-command: "make" %
% End: %
