Index: doc/generic_types/generic_types.tex
===================================================================
--- doc/generic_types/generic_types.tex	(revision d9c8a597c64732b01c6014a27959e095f47857ef)
+++ doc/generic_types/generic_types.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -1,8 +1,57 @@
+% take of review (for line numbers) and anonymous (for anonymization) on submission
 \documentclass[format=acmlarge, anonymous, review]{acmart}
 
+\usepackage{listings}	% For code listings
+
+% Useful macros
+\newcommand{\CFA}{C$\mathbf\forall$} % Cforall symbolic name
+\newcommand{\CC}{\rm C\kern-.1em\hbox{+\kern-.25em+}} % C++ symbolic name
+\newcommand{\CCeleven}{\rm C\kern-.1em\hbox{+\kern-.25em+}11} % C++11 symbolic name
+\newcommand{\CCfourteen}{\rm C\kern-.1em\hbox{+\kern-.25em+}14} % C++14 symbolic name
+\newcommand{\CCseventeen}{\rm C\kern-.1em\hbox{+\kern-.25em+}17} % C++17 symbolic name
+
+\newcommand{\TODO}{\textbf{TODO}}
+\newcommand{\eg}{\textit{e}.\textit{g}.}
+\newcommand{\ie}{\textit{i}.\textit{e}.}
+\newcommand{\etc}{\textit{etc}.}
+
+% 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,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
+% extendedchars=true,									% allow ASCII characters in the range 128-255
+% escapechar=§,											% LaTeX escape in CFA code §...§ (section symbol), emacs: C-q M-'
+mathescape=true,										% LaTeX math 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 {->}{$\rightarrow$}2,
+% moredelim=**[is][\color{red}]{®}{®},					% red highlighting ®...® (registered trademark symbol) emacs: C-q M-.
+% moredelim=**[is][\color{blue}]{ß}{ß},					% blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_
+% moredelim=**[is][\color{OliveGreen}]{¢}{¢}, 			% green highlighting ¢...¢ (cent symbol) emacs: C-q M-"
+% moredelim=[is][\lstset{keywords={}}]{¶}{¶}, 			% keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^
+}% lstset
+
+% inline code @...@
+\lstMakeShortInline@
+
+% ACM Information
 \citestyle{acmauthoryear}
-
-\newcommand{\CFA}{C$\mathbf\forall$}
-\newcommand{\TODO}{\textbf{TODO}}
 
 \acmJournal{PACMPL}
@@ -21,4 +70,28 @@
 }
 \email{a3moss@uwaterloo.ca}
+
+\author{Robert Schluntz}
+\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}
+}
+\email{rschlunt@uwaterloo.ca}
+
+\author{Peter Buhr}
+\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}
+}
+\email{pabuhr@uwaterloo.ca}
 
 \terms{generic, types}
@@ -49,5 +122,4 @@
 \ccsdesc[300]{Software and its engineering~Source code generation}
 
-% \abstract{Abstract goes here.}
 \begin{abstract}
 \TODO{} Write abstract.
@@ -59,7 +131,182 @@
 
 \section{Introduction \& Background}
-\CFA{}\footnote{Pronounced ``C-for-all'', and written \CFA{} or Cforall.} is an evolutionary modernization of the C programming language which aims to add modern language features to C while maintaining both source compatibility with C and a familiar mental model for programmers. This paper describes how generic types are designed and implemented in \CFA{}, and how they interact with \CFA{}'s polymorphic functions.
-
-\CFA{}'s polymorphism was originally formalized by \citet{Ditchfield92}, and first implemented by \citet{Bilson03}.
+
+\CFA{}\footnote{Pronounced ``C-for-all'', and written \CFA{} or Cforall.} is an evolutionary extension of the C programming language which aims to add modern language features to C while maintaining both source compatibility with C and a familiar mental model for programmers. This paper describes how generic types are designed and implemented in \CFA{}, and how they interact with \CFA{}'s polymorphic functions.
+
+\subsection{Polymorphic Functions}
+
+\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 x) {is_
+    return x;
+}
+
+int forty_two = identity(42); // 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@, which 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, 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 separate compilation.
+
+Since bare polymorphic types do not provide a great range of available operations, \CFA{} provides a \emph{type assertion} mechanism to provide further information about a type:
+\begin{lstlisting}
+forall(otype T | { T twice(T); })
+T four_times(T x) {
+    return twice( twice(x) );
+}
+
+double twice(double d) { return d * 2.0; } // (1)
+
+double magic = four_times(10.5); // T is bound to double, uses (1) to satisfy type assertion
+\end{lstlisting}
+These type assertions may be either variable or function declarations that depend on a polymorphic type variable. @four_times@ can only be called with an argument for which there exists a function named @twice@ that can take that argument and return another value of the same type; a pointer to the appropriate @twice@ function is passed as an additional implicit parameter to the call of @four_times@.
+
+Monomorphic specializations of polymorphic functions can themselves be used to satisfy type assertions. For instance, @twice@ could have been defined using the \CFA{} syntax for operator overloading as:
+\begin{lstlisting}
+forall(otype S | { S ?+?(S, S); })
+S twice(S x) { return x + x; }  // (2)
+\end{lstlisting} 
+This version of @twice@ works for any type @S@ that has an addition operator defined for it, and it could have been used to satisfy the type assertion on @four_times@. 
+The compiler accomplishes this by creating a wrapper function calling @twice // (2)@ with @S@ bound to @double@, then providing this wrapper function to @four_times@\footnote{\lstinline@twice // (2)@ could also have had a type parameter named \lstinline@T@; \CFA{} specifies renaming of the type parameters, which would avoid the name conflict with the type variable \lstinline@T@ of \lstinline@four_times@.}.
+
+\subsection{Traits}
+
+\CFA{} provides \emph{traits} as a means to name a group of type assertions, as in the example below:
+\begin{lstlisting}
+trait has_magnitude(otype T) {
+    bool ?<?(T, T);  // comparison operator for T
+    T -?(T);  // negation operator for T
+    void ?{}(T*, zero_t);  // constructor from 0 literal
+};
+
+forall(otype M | has_magnitude(M))
+M abs( M m ) {
+    M zero = { 0 };  // 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}
+
+@otype@ is essentially syntactic sugar for the following trait:
+\begin{lstlisting}
+trait otype(dtype T | sized(T)) {
+	// sized is a compiler-provided pseudo-trait for types with known size & alignment
+	void ?{}(T*);  // default constructor
+	void ?{}(T*, T);  // copy constructor
+	T ?=?(T*, T);  // assignment operator
+	void ^?{}(T*);  // destructor
+};
+\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;  // int now satisfies the nominal trait
+{
+    char is_nominal; // char satisfies the nominal trait
+}
+// char no longer satisfies the nominal trait here  
+\end{lstlisting}
+
+Traits, however, are significantly more powerful than nominal-inheritance interfaces; firstly, due to the scoping rules of the declarations that satisfy a trait's type assertions, a type may not satisfy a trait everywhere that the type is declared, as with @char@ and the @nominal@ trait above. Secondly, 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); // Ptr can be dereferenced into a modifiable value of type El
+}
+
+struct list {
+    int value;
+    list *next;  // 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}
+
+The generic types design for \CFA{} must integrate 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 should not be 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; \CFA{} refers to such types as \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*@ will have exactly the same in-memory representation as a @void*@, and can therefore be represented by a @void*@ in code generation.
+
+The \CFA{} compiler 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 interoperation between equivalent instantiations of a generic type, the compiler saves the set of instantiations currently in scope and re-uses the generated struct declarations where appropriate. As an example, the concrete instantiation for @pair(const char*, int)@ would look something 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 would look something like this, and be 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}
+
+\TODO{} Maybe move this after the rest of the discussion.
+This re-use 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{} will be effectively identical to a version of this written in standard C using @void*@, yet the \CFA{} version will be type-checked to ensure that the fields of both pairs and the arguments to the comparison function match in type.
+
+\TODO{} The second is zero-cost ``tag'' structs.
+
+\section{Tuples}
+
+\TODO{} Integrate Rob's work
+
+\TODO{} Check if we actually can use ttype parameters on generic types (if they set the complete flag, it should work, or nearly so).
+
+\section{Related Work}
+
+\TODO{} Talk about \CC{}, Cyclone, \etc{}
+
+\section{Conclusion}
+
+\TODO{}
 
 \bibliographystyle{ACM-Reference-Format}
Index: doc/rob_thesis/cfa-format.tex
===================================================================
--- doc/rob_thesis/cfa-format.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/cfa-format.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,191 @@
+\usepackage{xcolor}
+\usepackage{listings}
+% \usepackage{booktabs}
+% \usepackage{array}
+% \newcolumntype{?}{!{\vrule width 1pt}} % thick vertical line
+
+
+% like Mac Classic or iPlastic
+% \definecolor{basicCol}{HTML}{000000}
+% \definecolor{commentCol}{HTML}{0066FF}
+% \definecolor{stringCol}{HTML}{036A07}
+% \definecolor{keywordCol}{HTML}{0000FF}
+% \definecolor{identifierCol}{HTML}{318495}
+
+% like Visual Studio 2010
+% \definecolor{basicCol}{HTML}{000000}
+% \definecolor{commentCol}{HTML}{006400}
+% \definecolor{stringCol}{HTML}{A31515}
+% \definecolor{keywordCol}{HTML}{0000FF}
+% \definecolor{identifierCol}{HTML}{000000}
+
+\definecolor{basicCol}{HTML}{000000}
+\definecolor{commentCol}{HTML}{000000}
+\definecolor{stringCol}{HTML}{000000}
+\definecolor{keywordCol}{HTML}{000000}
+\definecolor{identifierCol}{HTML}{000000}
+
+% from https://gist.github.com/nikolajquorning/92bbbeef32e1dd80105c9bf2daceb89a
+\lstdefinelanguage{sml} {
+  morekeywords= {
+    EQUAL, GREATER, LESS, NONE, SOME, abstraction, abstype, and, andalso, array, as, before, bool, case, char, datatype, do, else, end, eqtype, exception, exn, false, fn, fun, functor, handle, if, in, include, infix, infixr, int, let, list, local, nil, nonfix, not, o, of, op, open, option, orelse, overload, print, raise, real, rec, ref, sharing, sig, signature, string, struct, structure, substring, then, true, type, unit, val, vector, where, while, with, withtype, word
+  },
+  morestring=[b]",
+  morecomment=[s]{(*}{*)},
+}
+
+\lstdefinelanguage{D}{
+  % Keywords
+  morekeywords=[1]{
+    abstract, alias, align, auto, body, break, cast, catch, class, const,
+    continue, debug, delegate, delete, deprecated, do, else, enum, export,
+    false, final, finally, for, foreach, foreach_reverse, function, goto, if,
+    immutable, import, in, inout, interface, invariant, is, lazy, macro, mixin,
+    module, new, nothrow, null, out, override, package, pragma, private,
+    protected, public, pure, ref, return, shared, static, struct, super,
+    switch, synchronized, template, this, throw, true, try, typedef, typeid,
+    typeof, union, unittest, volatile, while, with
+  },
+  % Special identifiers, common functions
+  morekeywords=[2]{enforce},
+  % Ugly identifiers
+  morekeywords=[3]{
+    __DATE__, __EOF__, __FILE__, __LINE__, __TIMESTAMP__, __TIME__, __VENDOR__,
+    __VERSION__, __ctfe, __gshared, __monitor, __thread, __vptr, _argptr,
+    _arguments, _ctor, _dtor
+  },
+  % Basic types
+  morekeywords=[4]{
+     byte, ubyte, short, ushort, int, uint, long, ulong, cent, ucent, void,
+     bool, bit, float, double, real, ushort, int, uint, long, ulong, float,
+     char, wchar, dchar, string, wstring, dstring, ireal, ifloat, idouble,
+     creal, cfloat, cdouble, size_t, ptrdiff_t, sizediff_t, equals_t, hash_t
+  },
+  % Strings
+  morestring=[b]{"},
+  morestring=[b]{'},
+  morestring=[b]{`},
+  % Comments
+  comment=[l]{//},
+  morecomment=[s]{/*}{*/},
+  morecomment=[s][\color{blue}]{/**}{*/},
+  morecomment=[n]{/+}{+/},
+  morecomment=[n][\color{blue}]{/++}{+/},
+  % Options
+  sensitive=true
+}
+
+\newcommand{\KWC}{K-W C\xspace}
+
+\renewcommand{\ttdefault}{pcr}
+
+\lstdefinestyle{defaultStyle}{
+  escapeinside={@@},
+  basicstyle=\footnotesize\ttfamily\color{basicCol},
+  keywordstyle=\bfseries\color{keywordCol},
+  commentstyle=\itshape\color{commentCol},
+  identifierstyle=\color{identifierCol},
+  stringstyle=\color{stringCol},
+  mathescape=true,
+  columns=fixed,
+  aboveskip=4pt,                                  % spacing above/below code block
+  belowskip=3pt,
+  keepspaces=true,
+  frame=lines,
+  literate=,
+  showlines=true,                                 % show blank lines at end of code
+  showspaces=false,
+  showstringspaces=false,
+  escapechar=\$,
+  xleftmargin=\parindentlnth,                     % indent code to paragraph indentation
+  moredelim=[is][\color{red}\bfseries]{**R**}{**R**},    % red highlighting
+  % moredelim=* detects keywords, comments, strings, and other delimiters and applies their formatting
+  % moredelim=** allows cumulative application
+}
+\lstset{
+  language = CFA,
+  style=defaultStyle
+}
+\lstMakeShortInline[basewidth=0.5em,breaklines=true]@  % single-character for \lstinline
+
+\lstnewenvironment{cfacode}[1][]{
+  \lstset{
+    language = CFA,
+    style=defaultStyle,
+    #1
+    % belowcaptionskip=1\baselineskip,
+    % breaklines=true,
+    % frame=L,
+  }
+}{}
+
+\lstnewenvironment{cppcode}[1][]{
+  \lstset{
+    language = c++,
+    style=defaultStyle,
+    #1
+  }
+}{}
+
+\lstnewenvironment{javacode}[1][]{
+  \lstset{
+    language = java,
+    style=defaultStyle,
+    #1
+  }
+}{}
+
+\lstnewenvironment{scalacode}[1][]{
+  \lstset{
+    language = scala,
+    style=defaultStyle,
+    #1
+  }
+}{}
+
+\lstnewenvironment{smlcode}[1][]{
+  \lstset{
+    language = sml,
+    style=defaultStyle,
+    #1
+  }
+}{}
+
+\lstnewenvironment{dcode}[1][]{
+  \lstset{
+    language = D,
+    style=defaultStyle,
+    #1
+  }
+}{}
+
+\newcommand{\zero}{\lstinline{zero_t}\xspace}
+\newcommand{\one}{\lstinline{one_t}\xspace}
+\newcommand{\ateq}{\lstinline{\@=}\xspace}
+
+% \lstset{ %
+%   backgroundcolor=\color{white},
+%   basicstyle=\footnotesize,
+%   breakatwhitespace=false,
+%   breaklines=true,
+%   captionpos=b,
+%   commentstyle=\color{mygreen},
+%   escapeinside={\%*}{*)},
+%   extendedchars=true,
+%   frame=single,
+%   keywordstyle=\color{blue},
+%   language=Prolog,
+%   numbers=left,
+%   numbersep=5pt,
+%   numberstyle=\tiny\color{mygray},
+%   rulecolor=\color{black},
+%   showspaces=false,
+%   showstringspaces=false,
+%   showtabs=false,
+%   stepnumber=2,
+%   stringstyle=\color{mymauve},
+%   tabsize=2,
+%   title=\lstname,
+%   morekeywords={not,\},\{,preconditions,effects },
+%   deletekeywords={time}
+% }
Index: doc/rob_thesis/conclusions.tex
===================================================================
--- doc/rob_thesis/conclusions.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/conclusions.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,5 @@
+%======================================================================
+\chapter{Conclusions}
+%======================================================================
+
+Conclusion paragraphs.
Index: doc/rob_thesis/ctordtor.tex
===================================================================
--- doc/rob_thesis/ctordtor.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/ctordtor.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,1666 @@
+%======================================================================
+\chapter{Constructors and Destructors}
+%======================================================================
+
+% TODO: discuss move semantics; they haven't been implemented, but could be. Currently looking at alternative models. (future work)
+
+% TODO: as an experiment, implement Andrei Alexandrescu's ScopeGuard http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758?pgno=2
+% doesn't seem possible to do this without allowing ttype on generic structs?
+
+% If a Cforall constructor is in scope, C style initialization is
+% disabled by default.
+% * initialization rule: if any constructor is in scope for type T, try
+%   to find a matching constructor for the call. If there are no
+%   constructors in scope for type T, then attempt to fall back on
+%   C-style initialization.
+% + if this rule was not in place, it would be easy to accidentally
+%   use C-style initialization in certain cases, which could lead to
+%   subtle errors [2]
+% - this means we need special syntax if we want to allow users to force
+%   a C-style initialization (to give users more control)
+% - two different declarations in the same scope can be implicitly
+%   initialized differently. That is, there may be two objects of type
+%   T that are initialized differently because there is a constructor
+%   definition between them. This is not technically specific to
+%   constructors.
+
+% C-style initializers can be accessed with @= syntax
+% + provides a way to get around the requirement of using a constructor
+%   (for advanced programmers only)
+% - can break invariants in the type => unsafe
+% * provides a way of asserting that a variable is an instance of a
+%   C struct (i.e. a POD struct), and so will not be implicitly
+%   destructed (this can be useful at times, maybe mitigates the need
+%   for move semantics?) [3]
+% + can modernize a code base one step at a time
+
+% Cforall constructors can be used in expressions to initialize any
+% piece of memory.
+% + malloc() { ... } calls the appropriate constructor on the newly
+%   allocated space; the argument is moved into the constructor call
+%   without taking its address [4]
+% - with the above form, there is still no way to ensure that
+%   dynamically allocated objects are constructed. To resolve this,
+%   we might want a stronger "new" function which always calls the
+%   constructor, although how we accomplish that is currently still
+%   unresolved (compiler magic vs. better variadic functions?)
+% + This can be used as a placement syntax [5]
+% - can call the constructor on an object more than once, which could
+%   cause resource leaks and reinitialize const fields (can try to
+%   detect and prevent this in some cases)
+%   * compiler always tries to implicitly insert a ctor/dtor pair for
+%     non-@= objects.
+%     * For POD objects, this will resolve to an autogenerated or
+%       intrinsic function.
+%     * Intrinsic functions are not automatically called. Autogenerated
+%       are, because they may call a non-autogenerated function.
+%     * destructors are automatically inserted at appropriate branches
+%       (e.g. return, break, continue, goto) and at the end of the block
+%       in which they are declared.
+%   * For @= objects, the compiler never tries to interfere and insert
+%     constructor and destructor calls for that object. Copy constructor
+%     calls do not count, because the object is not the target of the copy
+%     constructor.
+
+% A constructor is declared with the name ?{}
+% + combines the look of C initializers with the precedent of ?() being
+%   the name for the function call operator
+% + it is possible to easily search for all constructors in a project
+%   and immediately know that a function is a constructor by seeing the
+%   name "?{}"
+
+% A destructor is declared with the name ^?{}
+% + name mirrors a constructor's name, with an extra symbol to
+%   distinguish it
+% - the symbol '~' cannot be used due to parsing conflicts with the
+%   unary '~' (bitwise negation) operator - this conflict exists because
+%   we want to allow users to write ^x{}; to destruct x, rather than
+%   ^?{}(&x);
+
+% The first argument of a constructor must be a pointer. The constructed
+% type is the base type of the pointer. E.g. void ?{}(T *) is a default
+% constructor for a T.
+% + can name the argument whatever you like, so not constrained by
+%   language keyword "this" or "self", etc.
+% - have to explicitly qualify all object members to initialize them
+%   (e.g. this->x = 0, rather than just x = 0)
+
+% Destructors can take arguments other than just the destructed pointer
+% * open research problem: not sure how useful this is
+
+% Pointer constructors
+% + can construct separately compiled objects (opaque types) [6]
+% + orthogonal design, follows directly from the definition of the first
+%   argument of a constructor
+% - may require copy constructor or move constructor (or equivalent)
+%   for correct implementation, which may not be obvious to everyone
+% + required feature for the prelude to specify as much behavior as possible
+%   (similar to pointer assignment operators in this respect)
+
+% Designations can only be used for C-style initialization
+% * designation for constructors is equivalent to designation for any
+%   general function call. Since a function prototype can be redeclared
+%   many times, with arguments named differently each time (or not at
+%   all!), this is considered to be an undesirable feature. We could
+%   construct some set of rules to allow this behaviour, but it is
+%   probably more trouble than it's worth, and no matter what we choose,
+%   it is not likely to be obvious to most people.
+
+% Constructing an anonymous member [7]
+% + same as with calling any other function on an anonymous member
+%   (implicit conversion by the compiler)
+% - may be some cases where this is ambiguous => clarify with a cast
+%   (try to design APIs to avoid sharing function signatures between
+%   composed types to avoid this)
+
+% Default Constructors and Destructors are called implicitly
+% + cannot forget to construct or destruct an object
+% - requires special syntax to specify that an object is not to be
+%   constructed (@=)
+% * an object will not be implicitly constructed OR destructed if
+%   explicitly initialized like a C object (@= syntax)
+% * an object will be destructed if there are no constructors in scope
+%   (even though it is initialized like a C object) [8]
+
+% An object which changes from POD type to non POD type will not change
+% the semantics of a type containing it by composition
+% * That is, constructors will not be regenerated at the point where
+%   an object changes from POD type to non POD type, because this could
+%   cause a cascade of constructors being regenerated for many other
+%   types. Further, there is precedence for this behaviour in other
+%   facets of Cforall's design, such as how nested functions interact.
+% * This behaviour can be simplified in a language without declaration
+%   before use, because a type can be classified as POD or non POD
+%   (rather than potentially changing between the two at some point) at
+%   at the global scope (which is likely the most common case)
+% * [9]
+
+% Move semantics
+% * <ongoing discussion about this. this will be filled in
+%    once we come to a consensus>
+
+% Changes to polymorphic type classes
+% * dtype and ftype remain the same
+% * forall(otype T) is currently essentially the same as
+%   forall(dtype T | { @size(T); void ?=?(T *, T); }).
+%   The big addition is that you can declare an object of type T, rather
+%   than just a pointer to an object of type T since you know the size,
+%   and you can assign into a T.
+%   * this definition is changed to add default constructor and
+%     destructor declarations, to remain consistent with what type meant
+%     before the introduction of constructors and destructors.
+%     * that is, forall(type T) is now essentially the same as
+%       forall(dtype T | { @size(T); void ?=?(T *, T);
+%                          void ?{}(T *); void ^?{}(T *); })
+%     + this is required to make generic types work correctly in
+%       polymorphic functions
+%     ? since declaring a constructor invalidates the autogenerated
+%       routines, it is possible for a type to have constructors, but
+%       not default constructors. That is, it might be the case that
+%       you want to write a polymorphic function for a type which has
+%       a size, but non-default constructors? Some options:
+%       * declaring a constructor as a part of the assertions list for
+%         a type declaration invalidates the default, so
+%         forall(otype T | { void ?{}(T *, int); })
+%         really means
+%         forall(dtype T | { @size(T); void ?=?(T *, T);
+%                            void ?{}(T *, int); void ^?{}(T *); })
+%       * force users to fully declare the assertions list like the
+%         above in this case (this seems very undesirable)
+%       * add another type class with the current desugaring of type
+%         (just size and assignment)
+%       * provide some way of subtracting from an existing assertions
+%         list (this might be useful to have in general)
+
+% Implementation issues:
+% Changes to prelude/autogen or built in defaults?
+% * pointer ctors/dtors [prelude]
+%   * other pointer type routines are declared in the prelude, and this
+%     doesn't seem like it should be any different
+% * basic type ctors/dtors [prelude]
+%   * other basic type routines are declared in the prelude, and this
+%     doesn't seem like it should be any different
+% ? aggregate types [undecided, but leaning towards autogenerate]
+%   * prelude
+%     * routines specific to aggregate types cannot be predeclared in
+%       the prelude because we don't know the name of every
+%       aggregate type in the entire program
+%   * autogenerate
+%     + default assignment operator is already autogenerated for
+%       aggregate types
+%       * this seems to lead us in the direction of autogenerating,
+%         because we may have a struct which contains other objects
+%         that require construction [10]. If we choose not to
+%         autogenerate in this case, then objects which are part of
+%         other objects by composition will not be constructed unless
+%         a constructor for the outer type is explicitly defined
+%       * in this case, we would always autogenerate the appropriate
+%         constructor(s) for an aggregate type, but just like with
+%         basic types, pointer types, and enum types, the constructor
+%         call can be elided when when it is not necessary.
+%     + constructors will have to be explicitly autogenerated
+%       in the case where they are required for a polymorphic function,
+%       when no user defined constructor is in scope, which may make it
+%       easiest to always autogenerate all appropriate constructors
+%     - n+2 constructors would have to be generated for a POD type
+%       * one constructor for each number of valid arguments [0, n],
+%         plus the copy constructor
+%         * this is taking a simplified approach: in C, it is possible
+%           to omit the enclosing braces in a declaration, which would
+%           lead to a combinatorial explosion of generated constructors.
+%           In the interest of keeping things tractable, Cforall may be
+%           incompatible with C in this case. [11]
+%       * for non-POD types, only autogenerate the default and copy
+%         constructors
+%       * alternative: generate only the default constructor and
+%         special case initialization for any other constructor when
+%         only the autogenerated one exists
+%         - this is not very sensible, as by the previous point, these
+%           constructors may be needed for polymorphic functions
+%           anyway.
+%     - must somehow distinguish in resolver between autogenerated and
+%       user defined constructors (autogenerated should never be chosen
+%       when a user defined option exists [check first parameter], even
+%       if full signature differs) (this may also have applications
+%       to other autogenerated routines?)
+%     - this scheme does not naturally support designation (i.e. general
+%       functions calls do not support designation), thus these cases
+%       will have to be treated specially in either case
+%   * defaults
+%     * i.e. hardcode a new set of rules for some "appropriate" default
+%       behaviour for
+%     + when resolving an initialization expression, explicitly check to
+%       see if any constructors are in scope. If yes, attempt to resolve
+%       to a constructor, and produce an error message if a match is not
+%       found. If there are no constructors in scope, resolve to
+%       initializing each field individually (C-style)
+%     + does not attempt to autogenerate constructors for POD types,
+%       which can be seen as a space optimization for the program
+%       binary
+%     - as stated previously, a polymorphic routine may require these
+%       autogenerated constructors, so this doesn't seem like a big win,
+%       because this leads to more complicated logic and tracking of
+%       which constructors have already been generated
+%     - even though a constructor is not explicitly declared or used
+%       polymorphically, we might still need one for all uses of a
+%       struct (e.g. in the case of composition).
+%   * the biggest tradeoff in autogenerating vs. defaulting appears to
+%     be in where and how the special code to check if constructors are
+%     present is handled. It appears that there are more reasons to
+%     autogenerate than not.
+
+% --- examples
+% [1] As an example of using constructors polymorphically, consider a
+% slight modification on the foldl example I put on the mailing list a
+% few months ago:
+
+% context iterable(type collection, type element, type iterator) {
+%   void ?{}(iterator *, collection); // used to be makeIterator, but can
+%                             // idiomatically use constructor
+%   int hasNext(iterator);
+%   iterator ++?(iterator *);
+%   lvalue element *?(iterator);
+% };
+
+
+% forall(type collection, type element, type result, type iterator
+%   | iterable(collection, element, iterator))
+% result foldl(collection c, result acc,
+%     result (*reduce)(result, element)) {
+%   iterator it = { c };
+%   while (hasNext(it)) {
+%     acc = reduce(acc, *it);
+%     ++it;
+%   }
+%   return acc;
+% }
+
+% Now foldl makes use of the knowledge that the iterator type has a
+% single argument constructor which takes the collection to iterate
+% over. This pattern allows polymorphic code to look more natural
+% (constructors are generally preferred to named initializer/creation
+% routines, e.g. "makeIterator")
+
+% [2] An example of some potentially dangerous code that we don't want
+% to let easily slip through the cracks - if this is really what you
+% want, then use @= syntax for the second declaration to quiet the
+% compiler.
+
+% struct A { int x, y, z; }
+% ?{}(A *, int);
+% ?{}(A *, int, int, int);
+
+% A a1 = { 1 };         // uses ?{}(A *, int);
+% A a2 = { 2, 3 };      // C-style initialization -> no invariants!
+% A a3 = { 4, 5, 6 };   // uses ?{}(A *, int, int, int);
+
+% [3] Since @= syntax creates a C object (essentially a POD, as far as
+% the compiler is concerned), the object will not be destructed
+% implicitly when it leaves scope, nor will it be copy constructed when
+% it is returned. In this case, a memcpy should be equivalent to a move.
+
+% // Box.h
+% struct Box;
+% void ?{}(Box **, int};
+% void ^?{}(Box **);
+% Box * make_fortytwo();
+
+% // Box.cfa
+% Box * make_fortytwo() {
+%   Box *b @= {};
+%   (&b){ 42 }; // construct explicitly
+%   return b; // no destruction, essentially a move?
+% }
+
+% [4] Cforall's typesafe malloc can be composed with constructor
+% expressions. It is possible for a user to define their own functions
+% similar to malloc and achieve the same effects (e.g. Aaron's example
+% of an arena allocator)
+
+% // CFA malloc
+% forall(type T)
+% T * malloc() { return (T *)malloc(sizeof(T)); }
+
+% struct A { int x, y, z; };
+% void ?{}(A *, int);
+
+% int foo(){
+%   ...
+%   // desugars to:
+%   // A * a = ?{}(malloc(), 123);
+%   A * a = malloc() { 123 };
+%   ...
+% }
+
+% [5] Aaron's example of combining function calls with constructor
+% syntax to perform an operation similar to C++'s std::vector::emplace
+% (i.e. to construct a new element in place, without the need to
+% copy)
+
+% forall(type T)
+% struct vector {
+%   T * elem;
+%   int len;
+%   ...
+% };
+
+% ...
+% forall(type T)
+% T * vector_new(vector(T) * v) {
+%   // reallocate if needed
+%   return &v->elem[len++];
+% }
+
+% int main() {
+%   vector(int) * v = ...
+%   vector_new(v){ 42 };  // add element to the end of vector
+% }
+
+% [6] Pointer Constructors. It could be useful to use the existing
+% constructor syntax even more uniformly for ADTs. With this, ADTs can
+% be initialized in the same manor as any other object in a polymorphic
+% function.
+
+% // vector.h
+% forall(type T) struct vector;
+% forall(type T) void ?{}(vector(T) **);
+% // adds an element to the end
+% forall(type T) vector(T) * ?+?(vector(T) *, T);
+
+% // vector.cfa
+% // don't want to expose the implementation to the user and/or don't
+% // want to recompile the entire program if the struct definition
+% // changes
+
+% forall(type T) struct vector {
+%   T * elem;
+%   int len;
+%   int capacity;
+% };
+
+% forall(type T) void resize(vector(T) ** v) { ... }
+
+% forall(type T) void ?{}(vector(T) ** v) {
+%   vector(T) * vect = *v = malloc();
+%   vect->capacity = 10;
+%   vect->len = 0;
+%   vect->elem = malloc(vect->capacity);
+% }
+
+% forall(type T) vector(T) * ?+?(vector(T) *v, T elem) {
+%   if (v->len == v->capacity) resize(&v);
+%   v->elem[v->len++] = elem;
+% }
+
+% // main.cfa
+% #include "adt.h"
+% forall(type T | { T ?+?(T, int); }
+% T sumRange(int lower, int upper) {
+%   T x;    // default construct
+%   for (int i = lower; i <= upper; i++) {
+%     x = x + i;
+%   }
+%   return x;
+% }
+
+% int main() {
+%   vector(int) * numbers = sumRange(1, 10);
+%   // numbers is now a vector containing [1..10]
+
+%   int sum = sumRange(1, 10);
+%   // sum is now an int containing the value 55
+% }
+
+% [7] The current proposal is to use the plan 9 model of inheritance.
+% Under this model, all of the members of an unnamed struct instance
+% become members of the containing struct. In addition, an object
+% can be passed as an argument to a function expecting one of its
+% base structs.
+
+% struct Point {
+%   double x;
+%   double y;
+% };
+
+% struct ColoredPoint {
+%   Point;        // anonymous member (no identifier)
+%                 // => a ColoredPoint has an x and y of type double
+%   int color;
+% };
+
+% ColoredPoint cp = ...;
+% cp.x = 10.3;    // x from Point is accessed directly
+% cp.color = 0x33aaff; // color is accessed normally
+% foo(cp);        // cp can be used directly as a Point
+
+% void ?{}(Point *p, double x, double y) {
+%   p->x = x;
+%   p->y = y;
+% }
+
+% void ?{}(ColoredPoint *cp, double x, double y, int color) {
+%   (&cp){ x, y };  // unambiguous, no ?{}(ColoredPoint*,double,double)
+%   cp->color = color;
+% }
+
+% struct Size {
+%   double width;
+%   double height;
+% };
+
+% void ?{}(Size *s, double w, double h) {
+%   p->width = w;
+%   p->height = h;
+% }
+
+% struct Foo {
+%   Point;
+%   Size;
+% }
+
+% ?{}(Foo &f, double x, double y, double w, double h) {
+%   // (&F,x,y) is ambiguous => is it ?{}(Point*,double,double) or
+%   // ?{}(Size*,double,double)? Solve with a cast:
+%   ((Point*)&F){ x, y };
+%   ((Size*)&F){ w, h };
+% }
+
+% [8] Destructors will be called on objects that were not constructed.
+
+% struct A { ... };
+% ^?{}(A *);
+% {
+%   A x;
+%   A y @= {};
+% } // x is destructed, even though it wasn't constructed
+%   // y is not destructed, because it is explicitly a C object
+
+
+% [9] A type's constructor is generated at declaration time using
+% current information about an object's members. This is analogous to
+% the treatment of other operators. For example, an object's assignment
+% operator will not change to call the override of a member's assignment
+% operator unless the object's assignment is also explicitly overridden.
+% This problem can potentially be treated differently in Do, since each
+% compilation unit is passed over at least twice (once to gather
+% symbol information, once to generate code - this is necessary to
+% achieve the "No declarations" goal)
+
+% struct A { ... };
+% struct B { A x; };
+% ...
+% void ?{}(A *);  // from this point on, A objects will be constructed
+% B b1;           // b1 and b1.x are both NOT constructed, because B
+%                 // objects are not constructed
+% void ?{}(B *);  // from this point on, B objects will be constructed
+% B b2;           // b2 and b2.x are both constructed
+
+% struct C { A x; };
+% // implicit definition of ?{}(C*), because C is not a POD type since
+% // it contains a non-POD type by composition
+% C c;            // c and c.x are both constructed
+
+% [10] Requiring construction by composition
+
+% struct A {
+%   ...
+% };
+
+% // declared ctor disables default c-style initialization of
+% // A objects; A is no longer a POD type
+% void ?{}(A *);
+
+% struct B {
+%   A x;
+% };
+
+% // B objects can not be C-style initialized, because A objects
+% // must be constructed => B objects are transitively not POD types
+% B b; // b.x must be constructed, but B is not constructible
+%      // => must autogenerate ?{}(B *) after struct B definition,
+%      // which calls ?{}(&b.x)
+
+% [11] Explosion in the number of generated constructors, due to strange
+% C semantics.
+
+% struct A { int x, y; };
+% struct B { A u, v, w; };
+
+% A a = { 0, 0 };
+
+% // in C, you are allowed to do this
+% B b1 = { 1, 2, 3, 4, 5, 6 };
+% B b2 = { 1, 2, 3 };
+% B b3 = { a, a, a };
+% B b4 = { a, 5, 4, a };
+% B b5 = { 1, 2, a, 3 };
+
+% // we want to disallow b1, b2, b4, and b5 in Cforall.
+% // In particular, we will autogenerate these constructors:
+% void ?{}(A *);             // default/0 parameters
+% void ?{}(A *, int);        // 1 parameter
+% void ?{}(A *, int, int);   // 2 parameters
+% void ?{}(A *, const A *);  // copy constructor
+
+% void ?{}(B *);             // default/0 parameters
+% void ?{}(B *, A);          // 1 parameter
+% void ?{}(B *, A, A);       // 2 parameters
+% void ?{}(B *, A, A, A);    // 3 parameters
+% void ?{}(B *, const B *);  // copy constructor
+
+% // we will not generate constructors for every valid combination
+% // of members in C. For example, we will not generate
+% void ?{}(B *, int, int, int, int, int, int);   // b1 would need this
+% void ?{}(B *, int, int, int);                  // b2 would need this
+% void ?{}(B *, A, int, int, A);                 // b4 would need this
+% void ?{}(B *, int, int, A, int);               // b5 would need this
+% // and so on
+
+
+
+% TODO: talk somewhere about compound literals?
+
+Since \CFA is a true systems language, it does not provide a garbage collector.
+As well, \CFA is not an object-oriented programming language, i.e. structures cannot have routine members.
+Nevertheless, one important goal is to reduce programming complexity and increase safety.
+To that end, \CFA provides support for implicit pre/post-execution of routines for objects, via constructors and destructors.
+
+% TODO: this is old. remove or refactor
+% Manual resource management is difficult.
+% Part of the difficulty results from not having any guarantees about the current state of an object.
+% Objects can be internally composed of pointers that may reference resources which may or may not need to be manually released, and keeping track of that state for each object can be difficult for the end user.
+
+% Constructors and destructors provide a mechanism to bookend the lifetime of an object, allowing the designer of a type to establish invariants for objects of that type.
+% Constructors guarantee that object initialization code is run before the object can be used, while destructors provide a mechanism that is guaranteed to be run immediately before an object's lifetime ends.
+% Constructors and destructors can help to simplify resource management when used in a disciplined way.
+% In particular, when all resources are acquired in a constructor, and all resources are released in a destructor, no resource leaks are possible.
+% This pattern is a popular idiom in several languages, such as \CC, known as RAII (Resource Acquisition Is Initialization).
+
+This chapter details the design of constructors and destructors in \CFA, along with their current implementation in the translator.
+Generated code samples have been edited to provide comments for clarity and to save on space.
+
+\section{Design Criteria}
+\label{s:Design}
+In designing constructors and destructors for \CFA, the primary goals were ease of use and maintaining backwards compatibility.
+
+In C, when a variable is defined, its value is initially undefined unless it is explicitly initialized or allocated in the static area.
+\begin{cfacode}
+int main() {
+  int x;        // uninitialized
+  int y = 5;    // initialized to 5
+  x = y;        // assigned 5
+  static int z; // initialized to 0
+}
+\end{cfacode}
+In the example above, @x@ is defined and left uninitialized, while @y@ is defined and initialized to 5.
+Next, @x@ is assigned the value of @y@.
+In the last line, @z@ is implicitly initialized to 0 since it is marked @static@.
+The key difference between assignment and initialization being that assignment occurs on a live object (i.e. an object that contains data).
+It is important to note that this means @x@ could have been used uninitialized prior to being assigned, while @y@ could not be used uninitialized.
+Use of uninitialized variables yields undefined behaviour, which is a common source of errors in C programs. % TODO: *citation*
+
+Declaration initialization is insufficient, because it permits uninitialized variables to exist and because it does not allow for the insertion of arbitrary code before the variable is live.
+Many C compilers give good warnings most of the time, but they cannot in all cases.
+\begin{cfacode}
+int f(int *);  // never reads the parameter, only writes
+int g(int *);  // reads the parameter - expects an initialized variable
+
+int x, y;
+f(&x);  // okay - only writes to x
+g(&y);  // will use y uninitialized
+\end{cfacode}
+Other languages are able to give errors in the case of uninitialized variable use, but due to backwards compatibility concerns, this cannot be the case in \CFA.
+
+In C, constructors and destructors are often mimicked by providing routines that create and teardown objects, where the teardown function is typically only necessary if the type modifies the execution environment.
+\begin{cfacode}
+struct array_int {
+  int * x;
+};
+struct array_int create_array(int sz) {
+  return (struct array_int) { malloc(sizeof(int)*sz) };
+}
+void destroy_rh(struct resource_holder * rh) {
+  free(rh->x);
+}
+\end{cfacode}
+This idiom does not provide any guarantees unless the structure is opaque, which then requires that all objects are heap allocated.
+\begin{cfacode}
+struct opqaue_array_int;
+struct opqaue_array_int * create_opqaue_array(int sz);
+void destroy_opaque_array(opaque_array_int *);
+int opaque_get(opaque_array_int *);  // subscript
+
+opaque_array_int * x = create_opaque_array(10);
+int x2 = opaque_get(x, 2);
+\end{cfacode}
+This pattern is cumbersome to use since every access becomes a function call.
+While useful in some situations, this compromise is too restrictive.
+Furthermore, even with this idiom it is easy to make mistakes, such as forgetting to destroy an object or destroying it multiple times.
+
+A constructor provides a way of ensuring that the necessary aspects of object initialization is performed, from setting up invariants to providing compile-time checks for appropriate initialization parameters.
+This goal is achieved through a guarantee that a constructor is called implicitly after every object is allocated from a type with associated constructors, as part of an object's definition.
+Since a constructor is called on every object of a managed type, it is impossible to forget to initialize such objects, as long as all constructors perform some sensible form of initialization.
+
+In \CFA, a constructor is a function with the name @?{}@.
+Every constructor must have a return type of @void@ and at least one parameter, the first of which is colloquially referred to as the \emph{this} parameter, as in many object-oriented programming-languages (however, a programmer can give it an arbitrary name).
+The @this@ parameter must have a pointer type, whose base type is the type of object that the function constructs.
+There is precedence for enforcing the first parameter to be the @this@ parameter in other operators, such as the assignment operator, where in both cases, the left-hand side of the equals is the first parameter.
+There is currently a proposal to add reference types to \CFA.
+Once this proposal has been implemented, the @this@ parameter will become a reference type with the same restrictions.
+
+Consider the definition of a simple type encapsulating a dynamic array of @int@s.
+
+\begin{cfacode}
+struct Array {
+  int * data;
+  int len;
+}
+\end{cfacode}
+
+In C, if the user creates an @Array@ object, the fields @data@ and @len@ are uninitialized, unless an explicit initializer list is present.
+It is the user's responsibility to remember to initialize both of the fields to sensible values.
+In \CFA, the user can define a constructor to handle initialization of @Array@ objects.
+
+\begin{cfacode}
+void ?{}(Array * arr){
+  arr->len = 10;    // default size
+  arr->data = malloc(sizeof(int)*arr->len);
+  for (int i = 0; i < arr->len; ++i) {
+    arr->data[i] = 0;
+  }
+}
+Array x;  // allocates storage for Array and calls ?{}(&x)
+\end{cfacode}
+
+This constructor initializes @x@ so that its @length@ field has the value 10, and its @data@ field holds a pointer to a block of memory large enough to hold 10 @int@s, and sets the value of each element of the array to 0.
+This particular form of constructor is called the \emph{default constructor}, because it is called on an object defined without an initializer.
+In other words, a default constructor is a constructor that takes a single argument, the @this@ parameter.
+
+In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}!.
+A destructor for the @Array@ type can be defined as such.
+\begin{cfacode}
+void ^?{}(Array * arr) {
+  free(arr->data);
+}
+\end{cfacode}
+Since the destructor is automatically called at deallocation for all objects of type @Array@, the memory associated with an @Array@ is automatically freed when the object's lifetime ends.
+The exact guarantees made by \CFA with respect to the calling of destructors are discussed in section \ref{sub:implicit_dtor}.
+
+As discussed previously, the distinction between initialization and assignment is important.
+Consider the following example.
+\begin{cfacode}[numbers=left]
+Array x, y;
+Array z = x;  // initialization
+y = x;        // assignment
+\end{cfacode}
+By the previous definition of the default constructor for @Array@, @x@ and @y@ are initialized to valid arrays of length 10 after their respective definitions.
+On line 3, @z@ is initialized with the value of @x@, while on line @4@, @y@ is assigned the value of @x@.
+The key distinction between initialization and assignment is that a value to be initialized does not hold any meaningful values, whereas an object to be assigned might.
+In particular, these cases cannot be handled the same way because in the former case @z@ does not currently own an array, while @y@ does.
+
+\begin{cfacode}[emph={other}, emphstyle=\color{red}]
+void ?{}(Array * arr, Array other) {  // copy constructor
+  arr->len = other.len;               // initialization
+  arr->data = malloc(sizeof(int)*arr->len)
+  for (int i = 0; i < arr->len; ++i) {
+    arr->data[i] = other.data[i];     // copy from other object
+  }
+}
+Array ?=?(Array * arr, Array other) { // assignment
+  ^?{}(arr);                          // explicitly call destructor
+  ?{}(arr, other);                    // explicitly call constructor
+  return *arr;
+}
+\end{cfacode}
+The two functions above handle these cases.
+The first function is called a \emph{copy constructor}, because it constructs its argument by copying the values from another object of the same type.
+The second function is the standard copy-assignment operator.
+These four functions are special in that they control the state of most objects.
+
+It is possible to define a constructor that takes any combination of parameters to provide additional initialization options.
+For example, a reasonable extension to the array type would be a constructor that allocates the array to a given initial capacity and initializes the array to a given @fill@ value.
+\begin{cfacode}
+void ?{}(Array * arr, int capacity, int fill) {
+  arr->len = capacity;
+  arr->data = malloc(sizeof(int)*arr->len);
+  for (int i = 0; i < arr->len; ++i) {
+    arr->data[i] = fill;
+  }
+}
+\end{cfacode}
+In \CFA, constructors are called implicitly in initialization contexts.
+\begin{cfacode}
+Array x, y = { 20, 0xdeadbeef }, z = y;
+\end{cfacode}
+In \CFA, constructor calls look just like C initializers, which allows them to be inserted into legacy C code with minimal code changes, and also provides a very simple syntax that veteran C programmers are familiar with.
+One downside of reusing C initialization syntax is that it isn't possible to determine whether an object is constructed just by looking at its declaration, since that requires knowledge of whether the type is managed at that point.
+
+This example generates the following code
+\begin{cfacode}
+Array x;
+?{}(&x);                  // implicit default construct
+Array y;
+?{}(&y, 20, 0xdeadbeef);  // explicit fill construct
+Array z;
+?{}(&z, y);               // copy construct
+^?{}(&z);                 // implicit destruct
+^?{}(&y);                 // implicit destruct
+^?{}(&x);                 // implicit destruct
+\end{cfacode}
+Due to the way that constructor calls are interleaved, it is impossible for @y@ to be referenced before it is initialized, except in its own constructor.
+This loophole is minor and exists in \CC as well.
+Destructors are implicitly called in reverse declaration-order so that objects with dependencies are destructed before the objects they are dependent on.
+
+\subsection{Syntax}
+\label{sub:syntax} % TODO: finish this section
+There are several ways to construct an object in \CFA.
+As previously introduced, every variable is automatically constructed at its definition, which is the most natural way to construct an object.
+\begin{cfacode}
+struct A { ... };
+void ?{}(A *);
+void ?{}(A *, A);
+void ?{}(A *, int, int);
+
+A a1;             // default constructed
+A a2 = { 0, 0 };  // constructed with 2 ints
+A a3 = a1;        // copy constructed
+// implicitly destruct a3, a2, a1, in that order
+\end{cfacode}
+Since constructors and destructors are just functions, the second way is to call the function directly.
+\begin{cfacode}
+struct A { int a; };
+void ?{}(A *);
+void ?{}(A *, A);
+void ^?{}(A *);
+
+A x;               // implicitly default constructed: ?{}(&x)
+A * y = malloc();  // copy construct: ?{}(&y, malloc())
+
+?{}(&x);    // explicit construct x
+?{}(y, x);  // explit construct y from x
+^?{}(&x);   // explicit destroy x
+^?{}(y);    // explicit destroy y
+
+// implicit ^?{}(&y);
+// implicit ^?{}(&x);
+\end{cfacode}
+Calling a constructor or destructor directly is a flexible feature that allows complete control over the management of a piece of storage.
+In particular, constructors double as a placement syntax.
+\begin{cfacode}
+struct A { ... };
+struct memory_pool { ... };
+void ?{}(memory_pool *, size_t);
+
+memory_pool pool = { 1024 };  // create an arena of size 1024
+
+A * a = allocate(&pool);      // allocate from memory pool
+?{}(a);                       // construct an A in place
+
+for (int i = 0; i < 10; i++) {
+  // reuse storage rather than reallocating
+  ^?{}(a);
+  ?{}(a);
+  // use a ...
+}
+^?{}(a);
+deallocate(&pool, a);         // return to memory pool
+\end{cfacode}
+Finally, constructors and destructors support \emph{operator syntax}.
+Like other operators in \CFA, the function name mirrors the use-case, in that the first $N$ arguments fill in the place of the question mark.
+\begin{cfacode}
+struct A { ... };
+struct B { A a; };
+
+A x, y, * z = &x;
+(&x){}          // default construct
+(&x){ y }       // copy construct
+(&x){ 1, 2, 3 } // construct with 3 arguments
+z{ y };         // copy construct x through a pointer
+^(&x){}         // destruct
+
+void ?{}(B * b) {
+  (&b->a){ 11, 17, 13 };  // construct a member
+}
+\end{cfacode}
+Constructor operator syntax has relatively high precedence, requiring parentheses around an address-of expression.
+Destructor operator syntax is actually an statement, and requires parentheses for symmetry with constructor syntax.
+
+\subsection{Function Generation}
+In \CFA, every type is defined to have the core set of four functions described previously.
+Having these functions exist for every type greatly simplifies the semantics of the language, since most operations can simply be defined directly in terms of function calls.
+In addition to simplifying the definition of the language, it also simplifies the analysis that the translator must perform.
+If the translator can expect these functions to exist, then it can unconditionally attempt to resolve them.
+Moreover, the existence of a standard interface allows polymorphic code to interoperate with new types seamlessly.
+
+To mimic the behaviour of standard C, the default constructor and destructor for all of the basic types and for all pointer types are defined to do nothing, while the copy constructor and assignment operator perform a bitwise copy of the source parameter (as in \CC).
+
+There are several options for user-defined types: structures, unions, and enumerations.
+To aid in ease of use, the standard set of four functions is automatically generated for a user-defined type after its definition is completed.
+By auto-generating these functions, it is ensured that legacy C code will continue to work correctly in every context where \CFA expects these functions to exist, since they are generated for every complete type.
+
+The generated functions for enumerations are the simplest.
+Since enumerations in C are essentially just another integral type, the generated functions behave in the same way that the builtin functions for the basic types work.
+% TODO: examples for enums
+For example, given the enumeration
+\begin{cfacode}
+enum Colour {
+  R, G, B
+};
+\end{cfacode}
+The following functions are automatically generated.
+\begin{cfacode}
+void ?{}(enum Colour *_dst){
+  // default constructor does nothing
+}
+void ?{}(enum Colour *_dst, enum Colour _src){
+  (*_dst)=_src;  // bitwise copy
+}
+void ^?{}(enum Colour *_dst){
+  // destructor does nothing
+}
+enum Colour ?=?(enum Colour *_dst, enum Colour _src){
+  return (*_dst)=_src; // bitwise copy
+}
+\end{cfacode}
+In the future, \CFA will introduce strongly-typed enumerations, like those in \CC.
+The existing generated routines will be sufficient to express this restriction, since they are currently set up to take in values of that enumeration type.
+Changes related to this feature only need to affect the expression resolution phase, where more strict rules will be applied to prevent implicit conversions from integral types to enumeration types, but should continue to permit conversions from enumeration types to @int@.
+In this way, it will still be possible to add an @int@ to an enumeration, but the resulting value will be an @int@, meaning that it won't be possible to reassign the value into an enumeration without a cast.
+
+For structures, the situation is more complicated.
+For a structure @S@ with members @M$_0$@, @M$_1$@, ... @M$_{N-1}$@, each function @f@ in the standard set calls \lstinline{f(s->M$_i$, ...)} for each @$i$@.
+That is, a default constructor for @S@ default constructs the members of @S@, the copy constructor with copy construct them, and so on.
+For example given the struct definition
+\begin{cfacode}
+struct A {
+  B b;
+  C c;
+}
+\end{cfacode}
+The following functions are implicitly generated.
+\begin{cfacode}
+void ?{}(A * this) {
+  ?{}(&this->b);  // default construct each field
+  ?{}(&this->c);
+}
+void ?{}(A * this, A other) {
+  ?{}(&this->b, other.b);  // copy construct each field
+  ?{}(&this->c, other.c);
+}
+A ?=?(A * this, A other) {
+  ?=?(&this->b, other.b);  // assign each field
+  ?=?(&this->c, other.c);
+}
+void ^?{}(A * this) {
+  ^?{}(&this->c);  // destruct each field
+  ^?{}(&this->b);
+}
+\end{cfacode}
+It is important to note that the destructors are called in reverse declaration order to resolve conflicts in the event there are dependencies among members.
+
+In addition to the standard set, a set of \emph{field constructors} is also generated for structures.
+The field constructors are constructors that consume a prefix of the struct's member list.
+That is, $N$ constructors are built of the form @void ?{}(S *, T$_{\text{M}_0}$)@, @void ?{}(S *, T$_{\text{M}_0}$, T$_{\text{M}_1}$)@, ..., @void ?{}(S *, T$_{\text{M}_0}$, T$_{\text{M}_1}$, ..., T$_{\text{M}_{N-1}}$)@, where members are copy constructed if they have a corresponding positional argument and are default constructed otherwise.
+The addition of field constructors allows structs in \CFA to be used naturally in the same ways that they could be used in C (i.e. to initialize any prefix of the struct), e.g., @A a0 = { b }, a1 = { b, c }@.
+Extending the previous example, the following constructors are implicitly generated for @A@.
+\begin{cfacode}
+void ?{}(A * this, B b) {
+  ?{}(&this->b, b);
+  ?{}(&this->c);
+}
+void ?{}(A * this, B b, C c) {
+  ?{}(&this->b, b);
+  ?{}(&this->c, c);
+}
+\end{cfacode}
+
+For unions, the default constructor and destructor do nothing, as it is not obvious which member if any should be constructed.
+For copy constructor and assignment operations, a bitwise @memcpy@ is applied.
+In standard C, a union can also be initialized using a value of the same type as its first member, and so a corresponding field constructor is generated to perform a bitwise @memcpy@ of the object.
+An alterantive to this design is to always construct and destruct the first member of a union, to match with the C semantics of initializing the first member of the union.
+This approach ultimately feels subtle and unsafe.
+Another option is to, like \CC, disallow unions from containing members that are themselves managed types.
+This restriction is a reasonable approach from a safety standpoint, but is not very C-like.
+Since the primary purpose of a union is to provide low-level memory optimization, it is assumed that the user has a certain level of maturity.
+It is therefore the responsibility of the user to define the special functions explicitly if they are appropriate, since it is impossible to accurately predict the ways that a union is intended to be used at compile-time.
+
+For example, given the union
+\begin{cfacode}
+union X {
+  Y y;
+  Z z;
+};
+\end{cfacode}
+The following functions are automatically generated.
+\begin{cfacode}
+void ?{}(union X *_dst){  // default constructor
+}
+void ?{}(union X *_dst, union X _src){  // copy constructor
+  __builtin_memcpy(_dst, &_src, sizeof(union X ));
+}
+void ^?{}(union X *_dst){  // destructor
+}
+union X ?=?(union X *_dst, union X _src){  // assignment
+  __builtin_memcpy(_dst, &_src, sizeof(union X));
+  return _src;
+}
+void ?{}(union X *_dst, struct Y src){  // construct first field
+  __builtin_memcpy(_dst, &src, sizeof(struct Y));
+}
+\end{cfacode}
+
+% This feature works in the \CFA model, since constructors are simply special functions and can be called explicitly, unlike in \CC. % this sentence isn't really true => placement new
+In \CCeleven, this restriction has been loosened to allow unions with managed members, with the caveat that any if there are any members with a user-defined operation, then that operation is not implicitly defined, forcing the user to define the operation if necessary.
+This restriction could easily be added into \CFA once \emph{deleted} functions are added.
+
+\subsection{Using Constructors and Destructors}
+Implicitly generated constructor and destructor calls ignore the outermost type qualifiers, e.g. @const@ and @volatile@, on a type by way of a cast on the first argument to the function.
+For example,
+\begin{cfacode}
+struct S { int i; };
+void ?{}(S *, int);
+void ?{}(S *, S);
+
+const S s = { 11 };
+volatile S s2 = s;
+\end{cfacode}
+Generates the following code
+\begin{cfacode}
+const struct S s;
+?{}((struct S *)&s, 11);
+volatile struct S s2;
+?{}((struct S *)&s2, s);
+\end{cfacode}
+Here, @&s@ and @&s2@ are cast to unqualified pointer types.
+This mechanism allows the same constructors and destructors to be used for qualified objects as for unqualified objects.
+Since this applies only to implicitly generated constructor calls, the language does not allow qualified objects to be re-initialized with a constructor without an explicit cast.
+
+Unlike \CC, \CFA provides an escape hatch that allows a user to decide at an object's definition whether it should be managed or not.
+An object initialized with \ateq is guaranteed to be initialized like a C object, and has no implicit destructor call.
+This feature provides all of the freedom that C programmers are used to having to optimize a program, while maintaining safety as a sensible default.
+\begin{cfacode}
+struct A { int * x; };
+// RAII
+void ?{}(A * a) { a->x = malloc(sizeof(int)); }
+void ^?{}(A * a) { free(a->x); }
+
+A a1;           // managed
+A a2 @= { 0 };  // unmanaged
+\end{cfacode}
+In this example, @a1@ is a managed object, and thus is default constructed and destructed at the end of @a1@'s lifetime, while @a2@ is an unmanaged object and is not implicitly constructed or destructed.
+Instead, @a2->x@ is initialized to @0@ as if it were a C object, due to the explicit initializer.
+Existing constructors are ignored when \ateq is used, so that any valid C initializer is able to initialize the object.
+
+In addition to freedom, \ateq provides a simple path to migrating legacy C code to Cforall, in that objects can be moved from C-style initialization to \CFA gradually and individually.
+It is worth noting that the use of unmanaged objects can be tricky to get right, since there is no guarantee that the proper invariants are established on an unmanaged object.
+It is recommended that most objects be managed by sensible constructors and destructors, except where absolutely necessary.
+
+When the user declares any constructor or destructor, the corresponding intrinsic/generated function and all field constructors for that type are hidden, so that they will not be found during expression resolution unless the user-defined function goes out of scope.
+Furthermore, if the user declares any constructor, then the intrinsic/generated default constructor is also hidden, making it so that objects of a type may not be default constructable.
+This closely mirrors the rule for implicit declaration of constructors in \CC, wherein the default constructor is implicitly declared if there is no user-declared constructor. % TODO: cite C++98 page 186??
+\begin{cfacode}
+struct S { int x, y; };
+
+void f() {
+  S s0, s1 = { 0 }, s2 = { 0, 2 }, s3 = s2;  // okay
+  {
+    void ?{}(S * s, int i) { s->x = i*2; }
+    S s4;  // error
+    S s5 = { 3 };  // okay
+    S s6 = { 4, 5 };  // error
+    S s7 = s5; // okay
+  }
+  S s8, s9 = { 6 }, s10 = { 7, 8 }, s11 = s10;  // okay
+}
+\end{cfacode}
+In this example, the inner scope declares a constructor from @int@ to @S@, which hides the default constructor and field constructors until the end of the scope.
+
+When defining a constructor or destructor for a struct @S@, any members that are not explicitly constructed or destructed are implicitly constructed or destructed automatically.
+If an explicit call is present, then that call is taken in preference to any implicitly generated call.
+A consequence of this rule is that it is possible, unlike \CC, to precisely control the order of construction and destruction of subobjects on a per-constructor basis, whereas in \CC subobject initialization and destruction is always performed based on the declaration order.
+\begin{cfacode}
+struct A {
+  B w, x, y, z;
+};
+void ?{}(A * a, int i) {
+  (&a->x){ i };
+  (&a->z){ a->y };
+}
+\end{cfacode}
+Generates the following
+\begin{cfacode}
+void ?{}(A * a, int i) {
+  (&a->w){};   // implicit default ctor
+  (&a->y){};   // implicit default ctor
+  (&a->x){ i };
+  (&a->z){ a->y };
+}
+\end{cfacode}
+Finally, it is illegal for a subobject to be explicitly constructed for the first time after it is used for the first time.
+If the translator cannot be reasonably sure that an object is constructed prior to its first use, but is constructed afterward, an error is emitted.
+More specifically, the translator searches the body of a constructor to ensure that every subobject is initialized.
+\begin{cfacode}
+void ?{}(A * a, double x) {
+  f(a->x);
+  (&a->x){ (int)x }; // error, used uninitialized on previous line
+}
+\end{cfacode}
+However, if the translator sees a subobject used within the body of a constructor, but does not see a constructor call that uses the subobject as the target of a constructor, then the translator assumes the object is to be implicitly constructed (copy constructed in a copy constructor and default constructed in any other constructor).
+\begin{cfacode}
+void ?{}(A * a) {
+  // default constructs all members
+  f(a->x);
+}
+
+void ?{}(A * a, A other) {
+  // copy constructs all members
+  f(a->y);
+}
+
+void ^?{}(A * a) {
+  ^(&a->x){}; // explicit destructor call
+} // z, y, w implicitly destructed, in this order
+\end{cfacode}
+If at any point, the @this@ parameter is passed directly as the target of another constructor, then it is assumed that constructor handles the initialization of all of the object's members and no implicit constructor calls are added. % TODO: confirm that this is correct. It might be possible to get subtle errors if you initialize some members then call another constructor... -- in fact, this is basically always wrong. if anything, I should check that such a constructor does not initialize any members, otherwise it'll always initialize the member twice (once locally, once by the called constructor).
+To override this rule, \ateq can be used to force the translator to trust the programmer's discretion.
+This form of \ateq is not yet implemented.
+
+Despite great effort, some forms of C syntax do not work well with constructors in \CFA.
+In particular, constructor calls cannot contain designations (see \ref{sub:c_background}), since this is equivalent to allowing designations on the arguments to arbitrary function calls.
+In C, function prototypes are permitted to have arbitrary parameter names, including no names at all, which may have no connection to the actual names used at function definition.
+Furthermore, a function prototype can be repeated an arbitrary number of times, each time using different names.
+\begin{cfacode}
+// all legal forward declarations in C
+void f(int, int, int);
+void f(int a, int b, int c);
+void f(int b, int c, int a);
+void f(int c, int a, int b);
+void f(int x, int y, int z);
+
+f(b:10, a:20, c:30);  // which parameter is which?
+\end{cfacode}
+As a result, it was decided that any attempt to resolve designated function calls with C's function prototype rules would be brittle, and thus it is not sensible to allow designations in constructor calls.
+% Many other languages do allow named arguments, such as Python and Scala, but they do not allow multiple arbitrarily named forward declarations of a function.
+
+In addition, constructor calls cannot have a nesting depth greater than the number of array components in the type of the initialized object, plus one.
+For example,
+\begin{cfacode}
+struct A;
+void ?{}(A *, int);
+void ?{}(A *, A, A);
+
+A a1[3] = { { 3 }, { 4 }, { 5 } };
+A a2[2][2] = {
+  { { 9 }, { 10 } },  // a2[0]
+  { {14 }, { 15 } }   // a2[1]
+};
+A a3[4] = {
+  { { 11 }, { 12 } },  // error
+  { 80 }, { 90 }, { 100 }
+}
+\end{cfacode}
+% TODO: in CFA if the array dimension is empty, no object constructors are added -- need to fix this.
+The body of @A@ has been omitted, since only the constructor interfaces are important.
+In C, having a greater nesting depth means that the programmer intends to initialize subobjects with the nested initializer.
+The reason for this omission is to both simplify the mental model for using constructors, and to make initialization simpler for the expression resolver.
+If this were allowed, it would be necessary for the expression resolver to decide whether each argument to the constructor call could initialize to some argument in one of the available constructors, making the problem highly recursive and potentially much more expensive.
+That is, in the previous example the line marked as an error could mean construct using @?{}(A *, A, A)@, since the inner initializer @{ 11 }@ could be taken as an intermediate object of type @A@ constructed with @?{}(A *, int)@.
+In practice, however, there could be many objects that can be constructed from a given @int@ (or, indeed, any arbitrary parameter list), and thus a complete solution to this problem would require fully exploring all possibilities.
+It should be noted that unmanaged objects can still make use of designations and nested initializers in \CFA.
+
+\subsection{Implicit Destructors}
+\label{sub:implicit_dtor}
+Destructors are automatically called at the end of the block in which the object is declared.
+In addition to this, destructors are automatically called when statements manipulate control flow to leave a block in which the object is declared, e.g., with return, break, continue, and goto statements.
+The example below demonstrates a simple routine with multiple return statements.
+\begin{cfacode}
+struct A;
+void ^?{}(A *);
+
+void f(int i) {
+  A x;  // construct x
+  {
+    A y; // construct y
+    {
+      A z; // construct z
+      {
+        if (i == 0) return; // destruct x, y, z
+      }
+      if (i == 1) return; // destruct x, y, z
+    } // destruct z
+    if (i == 2) return; // destruct x, y
+  } // destruct y
+}
+\end{cfacode}
+
+%% having this feels excessive, but it's here if necessary
+% This procedure generates the following code.
+% \begin{cfacode}
+% void f(int i){
+%   struct A x;
+%   ?{}(&x);
+%   {
+%     struct A y;
+%     ?{}(&y);
+%     {
+%       struct A z;
+%       ?{}(&z);
+%       {
+%         if ((i==0)!=0) {
+%           ^?{}(&z);
+%           ^?{}(&y);
+%           ^?{}(&x);
+%           return;
+%         }
+%       }
+%       if (((i==1)!=0) {
+%           ^?{}(&z);
+%           ^?{}(&y);
+%           ^?{}(&x);
+%           return ;
+%       }
+%       ^?{}(&z);
+%     }
+
+%     if ((i==2)!=0) {
+%       ^?{}(&y);
+%       ^?{}(&x);
+%       return;
+%     }
+%     ^?{}(&y);
+%   }
+
+%   ^?{}(&x);
+% }
+% \end{cfacode}
+
+The next example illustrates the use of simple continue and break statements and the manner that they interact with implicit destructors.
+\begin{cfacode}
+for (int i = 0; i < 10; i++) {
+  A x;
+  if (i == 2) {
+    continue;  // destruct x
+  } else if (i == 3) {
+    break;     // destruct x
+  }
+} // destruct x
+\end{cfacode}
+Since a destructor call is automatically inserted at the end of the block, nothing special needs to happen to destruct @x@ in the case where control reaches the end of the loop.
+In the case where @i@ is @2@, the continue statement runs the loop update expression and attemps to begin the next iteration of the loop.
+Since continue is a C statement, which does not understand destructors, a destructor call is added just before the continue statement to ensure that @x@ is destructed.
+When @i@ is @3@, the break statement moves control to just past the end of the loop.
+Like the previous case, a destructor call for @x@ is inserted just before the break statement.
+
+\CFA also supports labelled break and continue statements, which allow more precise manipulation of control flow.
+Labelled break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure.
+\begin{cfacode}[emph={L1,L2}, emphstyle=\color{red}]
+L1: for (int i = 0; i < 10; i++) {
+  A x;
+  L2: for (int j = 0; j < 10; j++) {
+    A y;
+    if (j == 0) {
+      continue;    // destruct y
+    } else if (j == 1) {
+      break;       // destruct y
+    } else if (i == 1) {
+      continue L1; // destruct y
+    } else if (i == 2) {
+      break L1;    // destruct x,y
+    }
+  } // destruct y
+} // destruct X
+\end{cfacode}
+The statement @continue L1@ begins the next iteration of the outer for-loop.
+Since the semantics of continue require the loop update expression to execute, control branches to the \emph{end} of the outer for loop, meaning that the block destructor for @x@ can be reused, and it is only necessary to generate the destructor for @y@.
+Break, on the other hand, requires jumping out of the loop, so the destructors for both @x@ and @y@ are generated and inserted before the @break L1@ statement.
+
+Finally, an example which demonstrates goto.
+Since goto is a general mechanism for jumping to different locations in the program, a more comprehensive approach is required.
+For each goto statement $G$ and each target label $L$, let $S_G$ be the set of all managed variables alive at $G$, and let $S_L$ be the set of all managed variables alive at $L$.
+If at any $G$, $S_L \setminus S_G = \emptyset$, then the translator emits an error, because control flow branches from a point where the object is not yet live to a point where it is live, skipping the object's constructor.
+Then, for every $G$, the destructors for each variable in the set $S_G \setminus S_L$ is inserted directly before $G$, which ensures each object that is currently live at $G$, but not at $L$, is destructed before control branches.
+\begin{cfacode}
+int i = 0;
+{
+  L0: ;     // S_L0 = { x }
+    A y;
+  L1: ;     // S_L1 = { x }
+    A x;
+  L2: ;     // S_L2 = { y, x }
+    if (i == 0) {
+      ++i;
+      goto L1;    // S_G = { y, x }
+      // S_G-S_L1 = { x } => destruct x
+    } else if (i == 1) {
+      ++i;
+      goto L2;    // S_G = { y, x }
+      // S_G-S_L2 = {} => destruct nothing
+    } else if (i == 2) {
+      ++i;
+      goto L3;    // S_G = { y, x }
+      // S_G-S_L3 = {}
+    } else if (false) {
+      ++i;
+      A z;
+      goto L3;    // S_G = { z, y, x }
+      // S_G-S_L3 = { z } => destruct z
+    } else {
+      ++i;
+      goto L4;    // S_G = { y, x }
+      // S_G-S_L4 = { y, x } => destruct y, x
+    }
+  L3: ;    // S_L3 = { y, x }
+    goto L2;      // S_G = { y, x }
+    // S_G-S_L2 = {}
+}
+L4: ;  // S_L4 = {}
+if (i == 4) {
+  goto L0;        // S_G = {}
+  // S_G-S_L0 = {}
+}
+\end{cfacode}
+Labelled break and continue are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely goverened by these rules.
+
+The next example demonstrates the error case.
+\begin{cfacode}
+{
+    goto L1; // S_G = {}
+    // S_L1-S_G = { y } => error
+    A y;
+  L1: ; // S_L1 = { y }
+    A x;
+  L2: ; // S_L2 = { y, x }
+}
+goto L2; // S_G = {}
+// S_L2-S_G = { y, x } => error
+\end{cfacode}
+
+\subsection{Implicit Copy Construction}
+When a function is called, the arguments supplied to the call are subject to implicit copy construction (and destruction of the generated temporary), and the return value is subject to destruction.
+When a value is returned from a function, the copy constructor is called to pass the value back to the call site.
+Exempt from these rules are intrinsic and builtin functions.
+It should be noted that unmanaged objects are subject to copy constructor calls when passed as arguments to a function or when returned from a function, since they are not the \emph{target} of the copy constructor call.
+This is an important detail to bear in mind when using unmanaged objects, and could produce unexpected results when mixed with objects that are explicitly constructed.
+\begin{cfacode}
+struct A;
+void ?{}(A *);
+void ?{}(A *, A);
+void ^?{}(A *);
+
+A f(A x) {
+  return x;
+}
+
+A y, z @= {};
+identity(y);
+identity(z);
+\end{cfacode}
+Note that @z@ is copy constructed into a temporary variable to be passed as an argument, which is also destructed after the call.
+A special syntactic form, such as a variant of \ateq, could be implemented to specify at the call site that an argument should not be copy constructed, to regain some control for the C programmer.
+
+This generates the following
+\begin{cfacode}
+struct A f(struct A x){
+  struct A _retval_f;
+  ?{}((&_retval_f), x);
+  return _retval_f;
+}
+
+struct A y;
+?{}(&y);
+struct A z = { 0 };
+
+struct A _tmp_cp1;     // argument 1
+struct A _tmp_cp_ret0; // return value
+_tmp_cp_ret0=f((?{}(&_tmp_cp1, y) , _tmp_cp1)), _tmp_cp_ret0;
+^?{}(&_tmp_cp_ret0);   // return value
+^?{}(&_tmp_cp1);       // argument 1
+
+struct A _tmp_cp2;     // argument 1
+struct A _tmp_cp_ret1; // return value
+_tmp_cp_ret1=f((?{}(&_tmp_cp2, z), _tmp_cp2)), _tmp_cp_ret1;
+^?{}(&_tmp_cp_ret1);   // return value
+^?{}(&_tmp_cp2);       // argument 1
+^?{}(&y);
+\end{cfacode}
+
+A known issue with this implementation is that the return value of a function is not guaranteed to have the same address for its entire lifetime.
+Specifically, since @_retval_f@ is allocated and constructed in @f@ then returned by value, the internal data is bitwise copied into the caller's stack frame.
+This approach works out most of the time, because typically destructors need to only access the fields of the object and recursively destroy.
+It is currently the case that constructors and destructors which use the @this@ pointer as a unique identifier to store data externally will not work correctly for return value objects.
+Thus is it not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program.
+\begin{cfacode}
+A * external_data[32];
+int ext_count;
+struct A;
+void ?{}(A * a) {
+  // ...
+  external_data[ext_count++] = a;
+}
+void ^?{}(A * a) {
+  for (int i = 0; i < ext_count) {
+    if (a == external_data[i]) { // may never be true
+      // ...
+    }
+  }
+}
+\end{cfacode}
+In the above example, a global array of pointers is used to keep track of all of the allocated @A@ objects.
+Due to copying on return, the current object being destructed will not exist in the array if an @A@ object is ever returned by value from a function.
+
+This problem could be solved in the translator by mutating the function signatures so that the return value is moved into the parameter list.
+For example, the translator could restructure the code like so
+\begin{cfacode}
+void f(struct A x, struct A * _retval_f){
+  ?{}(_retval_f, x);  // construct directly into caller's stack frame
+}
+
+struct A y;
+?{}(&y);
+struct A z = { 0 };
+
+struct A _tmp_cp1;     // argument 1
+struct A _tmp_cp_ret0; // return value
+f((?{}(&_tmp_cp1, y) , _tmp_cp1), &_tmp_cp_ret0), _tmp_cp_ret0;
+^?{}(&_tmp_cp_ret0);   // return value
+^?{}(&_tmp_cp1);       // argument 1
+\end{cfacode}
+This transformation provides @f@ with the address of the return variable so that it can be constructed into directly.
+It is worth pointing out that this kind of signature rewriting already occurs in polymorphic functions which return by value, as discussed in \cite{Bilson03}.
+A key difference in this case is that every function would need to be rewritten like this, since types can switch between managed and unmanaged at different scope levels, e.g.
+\begin{cfacode}
+struct A { int v; };
+A x; // unmanaged
+{
+  void ?{}(A * a) { ... }
+  void ^?{}(A * a) { ... }
+  A y; // managed
+}
+A z; // unmanaged
+\end{cfacode}
+Hence there is not enough information to determine at function declaration to determine whether a type is managed or not, and thus it is the case that all signatures have to be rewritten to account for possible copy constructor and destructor calls.
+Even with this change, it would still be possible to declare backwards compatible function prototypes with an @extern "C"@ block, which allows for the definition of C-compatible functions within \CFA code, however this would require actual changes to the way code inside of an @extern "C"@ function is generated as compared with normal code generation.
+Furthermore, it isn't possible to overload C functions, so using @extern "C"@ to declare functions is of limited use.
+
+It would be possible to regain some control by adding an attribute to structs which specifies whether they can be managed or not (perhaps \emph{manageable} or \emph{unmanageable}), and to emit an error in the case that a constructor or destructor is declared for an unmanageable type.
+Ideally, structs should be manageable by default, since otherwise the default case becomes more verbose.
+This means that in general, function signatures would have to be rewritten, and in a select few cases the signatures would not be rewritten.
+\begin{cfacode}
+__attribute__((manageable)) struct A { ... };   // can declare constructors
+__attribute__((unmanageable)) struct B { ... }; // cannot declare constructors
+struct C { ... };                               // can declare constructors
+
+A f();  // rewritten void f(A *);
+B g();  // not rewritten
+C h();  // rewritten void h(C *);
+\end{cfacode}
+An alternative is to instead make the attribute \emph{identifiable}, which states that objects of this type use the @this@ parameter as an identity.
+This strikes more closely to the visibile problem, in that only types marked as identifiable would need to have the return value moved into the parameter list, and every other type could remain the same.
+Furthermore, no restrictions would need to be placed on whether objects can be constructed.
+\begin{cfacode}
+__attribute__((identifiable)) struct A { ... };  // can declare constructors
+struct B { ... };                                // can declare constructors
+
+A f();  // rewritten void f(A *);
+B g();  // not rewritten
+\end{cfacode}
+
+Ultimately, this is the type of transformation that a real compiler would make when generating assembly code.
+Since a compiler has full control over its calling conventions, it can seamlessly allow passing the return parameter without outwardly changing the signature of a routine.
+As such, it has been decided that this issue is not currently a priority.
+
+\section{Implementation}
+\subsection{Array Initialization}
+Arrays are a special case in the C type system.
+C arrays do not carry around their size, making it impossible to write a standalone \CFA function that constructs or destructs an array while maintaining the standard interface for constructors and destructors.
+Instead, \CFA defines the initialization and destruction of an array recursively.
+That is, when an array is defined, each of its elements is constructed in order from element 0 up to element $n-1$.
+When an array is to be implicitly destructed, each of its elements is destructed in reverse order from element $n-1$ down to element 0.
+As in C, it is possible to explicitly provide different initializers for each element of the array through array initialization syntax.
+In this case, each of the initializers is taken in turn to construct a subsequent element of the array.
+If too many initializers are provided, only the initializers up to N are actually used.
+If too few initializers are provided, then the remaining elements are default constructed.
+
+For example, given the following code.
+\begin{cfacode}
+struct X {
+  int x, y, z;
+};
+void f() {
+  X x[10] = { { 1, 2, 3 }, { 4 }, { 7, 8 } };
+}
+\end{cfacode}
+The following code is generated for @f@.
+\begin{cfacode}
+void f(){
+  struct X x[((long unsigned int )10)];
+  // construct x
+  {
+    int _index0 = 0;
+    // construct with explicit initializers
+    {
+      if (_index0<10) ?{}(&x[_index0], 1, 2, 3);
+      ++_index0;
+      if (_index0<10) ?{}(&x[_index0], 4);
+      ++_index0;
+      if (_index0<10) ?{}(&x[_index0], 7, 8);
+      ++_index0;
+    }
+
+    // default construct remaining elements
+    for (;_index0<10;++_index0) {
+      ?{}(&x[_index0]);
+    }
+  }
+  // destruct x
+  {
+    int _index1 = 10-1;
+    for (;_index1>=0;--_index1) {
+      ^?{}(&x[_index1]);
+    }
+  }
+}
+\end{cfacode}
+Multidimensional arrays require more complexity.
+For example, a two dimensional array
+\begin{cfacode}
+void g() {
+  X x[10][10] = {
+    { { 1, 2, 3 }, { 4 } }, // x[0]
+    { { 7, 8 } }            // x[1]
+  };
+}\end{cfacode}
+Generates the following
+\begin{cfacode}
+void g(){
+  struct X x[10][10];
+  // construct x
+  {
+    int _index0 = 0;
+    for (;_index0<10;++_index0) {
+      {
+        int _index1 = 0;
+        // construct with explicit initializers
+        {
+          switch ( _index0 ) {
+            case 0:
+              // construct first array
+              if ( _index1<10 ) ?{}(&x[_index0][_index1], 1, 2, 3);
+              ++_index1;
+              if ( _index1<10 ) ?{}(&x[_index0][_index1], 4);
+              ++_index1;
+              break;
+            case 1:
+              // construct second array
+              if ( _index1<10 ) ?{}(&x[_index0][_index1], 7, 8);
+              ++_index1;
+              break;
+          }
+        }
+        // default construct remaining elements
+        for (;_index1<10;++_index1) {
+            ?{}(&x[_index0][_index1]);
+        }
+      }
+    }
+  }
+  // destruct x
+  {
+    int _index2 = 10-1;
+    for (;_index2>=0;--_index2) {
+      {
+        int _index3 = 10-1;
+        for (;_index3>=0;--_index3) {
+            ^?{}(&x[_index2][_index3]);
+        }
+      }
+    }
+  }
+}
+\end{cfacode}
+% It is possible to generate slightly simpler code for the switch cases, since the value of @_index1@ is known at compile-time within each case, however the procedure for generating constructor calls is complicated.
+% It is simple to remove the increment statements for @_index1@, but it is not simple to remove the
+%% technically, it's not hard either. I could easily downcast and change the second argument to ?[?], but is it really necessary/worth it??
+
+\subsection{Global Initialization}
+In standard C, global variables can only be initialized to compile-time constant expressions.
+This places strict limitations on the programmer's ability to control the default values of objects.
+In \CFA, constructors and destructors are guaranteed to be run on global objects, allowing arbitrary code to be run before and after the execution of the main routine.
+By default, objects within a translation unit are constructed in declaration order, and destructed in the reverse order.
+The default order of construction of objects amongst translation units is unspecified.
+% TODO: not yet implemented, but g++ provides attribute init_priority, which allows specifying the order of global construction on a per object basis
+%   https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes
+% suggestion: implement this in CFA by picking objects with a specified priority and pulling them into their own init functions (could even group them by priority level -> map<int, list<ObjectDecl*>>) and pull init_priority forward into constructor and destructor attributes with the same priority level
+It is, however, guaranteed that any global objects in the standard library are initialized prior to the initialization of any object in the user program.
+
+This feature is implemented in the \CFA translator by grouping every global constructor call into a function with the GCC attribute \emph{constructor}, which performs most of the heavy lifting. % CITE: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes
+A similar function is generated with the \emph{destructor} attribute, which handles all global destructor calls.
+At the time of writing, initialization routines in the library are specified with priority \emph{101}, which is the highest priority level that GCC allows, whereas initialization routines in the user's code are implicitly given the default priority level, which ensures they have a lower priority than any code with a specified priority level.
+This mechanism allows arbitrarily complicated initialization to occur before any user code runs, making it possible for library designers to initialize their modules without requiring the user to call specific startup or teardown routines.
+
+For example, given the following global declarations.
+\begin{cfacode}
+struct X {
+  int y, z;
+};
+void ?{}(X *);
+void ?{}(X *, int, int);
+void ^?{}(X *);
+
+X a;
+X b = { 10, 3 };
+\end{cfacode}
+The following code is generated.
+\begin{cfacode}
+__attribute__ ((constructor)) static void _init_global_ctor(void){
+  ?{}(&a);
+  ?{}(&b, 10, 3);
+}
+__attribute__ ((destructor)) static void _destroy_global_ctor(void){
+  ^?{}(&b);
+  ^?{}(&a);
+}
+\end{cfacode}
+
+\subsection{Static Local Variables}
+In standard C, it is possible to mark variables that are local to a function with the @static@ storage class.
+Unlike normal local variables, a @static@ local variable is defined to live for the entire duration of the program, so that each call to the function has access to the same variable with the same address and value as it had in the previous call to the function. % TODO: mention dynamic loading caveat??
+Much like global variables, in C @static@ variables must be initialized to a \emph{compile-time constant value} so that a compiler is able to create storage for the variable and initialize it before the program begins running.
+
+Yet again, this rule is too restrictive for a language with constructors and destructors.
+Instead, \CFA modifies the definition of a @static@ local variable so that objects are guaranteed to be live from the time control flow reaches their declaration, until the end of the program, since the initializer expression is not necessarily a compile-time constant, but can depend on the current execution state of the function.
+Since standard C does not allow access to a @static@ local variable before the first time control flow reaches the declaration, this restriction does not preclude any valid C code.
+Local objects with @static@ storage class are only implicitly constructed and destructed once for the duration of the program.
+The object is constructed when its declaration is reached for the first time.
+The object is destructed once at the end of the program.
+
+Construction of @static@ local objects is implemented via an accompanying @static bool@ variable, which records whether the variable has already been constructed.
+A conditional branch checks the value of the companion @bool@, and if the variable has not yet been constructed then the object is constructed.
+The object's destructor is scheduled to be run when the program terminates using @atexit@, and the companion @bool@'s value is set so that subsequent invocations of the function will not reconstruct the object.
+Since the parameter to @atexit@ is a parameter-less function, some additional tweaking is required.
+First, the @static@ variable must be hoisted up to global scope and uniquely renamed to prevent name clashes with other global objects.
+Second, a function is built which calls the destructor for the newly hoisted variable.
+Finally, the newly generated function is registered with @atexit@, instead of registering the destructor directly.
+Since @atexit@ calls functions in the reverse order in which they are registered, @static@ local variables are guaranteed to be destructed in the reverse order that they are constructed, which may differ between multiple executions of the same program.
+
+Extending the previous example
+\begin{cfacode}
+int f(int x) {
+  static X a;
+  static X b = { x, x };  // depends on parameter value
+  static X c = b;         // depends on local variable
+}
+\end{cfacode}
+Generates the following.
+\begin{cfacode}
+static struct X a_static_var0;
+static void __a_dtor_atexit0(void){
+  ((void)^?{}(((struct X *)(&a_static_var0))));
+}
+static struct X b_static_var1;
+static void __b_dtor_atexit1(void){
+  ((void)^?{}(((struct X *)(&b_static_var1))));
+}
+static struct X c_static_var2;
+static void __c_dtor_atexit2(void){
+  ((void)^?{}(((struct X *)(&c_static_var2))));
+}
+int f(int x){
+  int _retval_f;
+  __attribute__ ((unused)) static void *_dummy0;
+  static _Bool __a_uninitialized = 1;
+  if ( __a_uninitialized ) {
+    ((void)?{}(((struct X *)(&a_static_var0))));
+    ((void)(__a_uninitialized=0));
+    ((void)atexit(__a_dtor_atexit0));
+  }
+
+  __attribute__ ((unused)) static void *_dummy1;
+  static _Bool __b_uninitialized = 1;
+  if ( __b_uninitialized ) {
+    ((void)?{}(((struct X *)(&b_static_var1)), x, x));
+    ((void)(__b_uninitialized=0));
+    ((void)atexit(__b_dtor_atexit1));
+  }
+
+  __attribute__ ((unused)) static void *_dummy2;
+  static _Bool __c_uninitialized = 1;
+  if ( __c_uninitialized ) {
+    ((void)?{}(((struct X *)(&c_static_var2)), b_static_var1));
+    ((void)(__c_uninitialized=0));
+    ((void)atexit(__c_dtor_atexit2));
+  }
+}
+\end{cfacode}
+
+\subsection{Constructor Expressions}
+In \CFA, it is possible to use a constructor as an expression.
+Like other operators, the function name @?{}@ matches its operator syntax.
+For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result.
+The significance of constructors as expressions rather than as statements is that the result of a constructor expression can be used as part of a larger expression.
+A key example is the use of constructor expressions to initialize the result of a call to standard C routine @malloc@.
+\begin{cfacode}
+struct X { ... };
+void ?{}(X *, double);
+X * x = malloc(sizeof(X)){ 1.5 };
+\end{cfacode}
+In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@.
+If this extension is not present, constructing dynamically allocated objects is much more cumbersome, requiring separate initialization of the pointer and initialization of the pointed-to memory.
+\begin{cfacode}
+X * x = malloc(sizeof(X));
+x{ 1.5 };
+\end{cfacode}
+Not only is this verbose, but it is also more error prone, since this form allows maintenance code to easily sneak in between the initialization of @x@ and the initialization of the memory that @x@ points to.
+This feature is implemented via a transformation produceing the value of the first argument of the constructor, since constructors do not themslves have a return value.
+Since this transformation results in two instances of the subexpression, care is taken to allocate a temporary variable to hold the result of the subexpression in the case where the subexpression may contain side effects.
+The previous example generates the following code.
+\begin{cfacode}
+struct X *_tmp_ctor;
+struct X *x = ?{}((_tmp_ctor=((_tmp_cp_ret0=
+  malloc(sizeof(struct X))), _tmp_cp_ret0))), 1.5), _tmp_ctor);
+\end{cfacode}
+It should be noted that this technique is not exclusive to @malloc@, and allows a user to write a custom allocator that can be idiomatically used in much the same way as a constructed @malloc@ call.
+
+It is also possible to use operator syntax with destructors.
+Unlike constructors, operator syntax with destructors is a statement and thus does not produce a value, since the destructed object is invalidated by the use of a destructor.
+For example, \lstinline!^(&x){}! calls the destructor on the variable @x@.
Index: doc/rob_thesis/examples/ctor/array_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/array_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/array_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,16 @@
+struct X { int x, y, z; };
+void ?{}(X *);
+void ?{}(X *, int);
+void ?{}(X *, int, int);
+void ?{}(X *, int, int, int);
+void ^?{}(X *);
+void f() {
+  X x[10] = { { 1, 2, 3 }, { 4 }, { 7, 8 } };
+}
+
+void g() {
+  X x[10][10] = {
+    { { 1, 2, 3 }, { 4 } },
+    { { 7, 8 } }
+  };
+}
Index: doc/rob_thesis/examples/ctor/copy_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/copy_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/copy_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,14 @@
+struct A;
+void ?{}(A *);
+void ?{}(A *, A);
+void ^?{}(A *);
+
+A f(A x) {
+  return x;
+}
+
+int main() {
+	A y, z @= {};
+	f(y);
+	f(z);
+}
Index: doc/rob_thesis/examples/ctor/cv_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/cv_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/cv_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,10 @@
+struct S { int i; };
+void ?{}(S *, int);
+void ?{}(S *, S);
+
+int main() {
+  const int i = 5;
+  volatile int j = i;
+  const S s = { 11 };
+  volatile S s2 = s;
+}
Index: doc/rob_thesis/examples/ctor/enum_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/enum_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/enum_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,3 @@
+enum Colour {
+  R, G, B
+};
Index: doc/rob_thesis/examples/ctor/expr_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/expr_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/expr_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,6 @@
+struct X {};
+void ?{}(X *, double);
+
+int f() {
+  X * x = malloc(sizeof(X)){ 1.5 };
+}
Index: doc/rob_thesis/examples/ctor/global_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/global_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/global_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,9 @@
+struct X {
+  int y, z;
+};
+void ?{}(X *);
+void ?{}(X *, int, int);
+void ^?{}(X *);
+
+X a;
+X b = { 10, 3 };
Index: doc/rob_thesis/examples/ctor/hide_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/hide_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/hide_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,12 @@
+struct S { int x; };
+
+int main() {
+  S s0; // okay
+  {
+    void ?{}(S * s, int i) { s->x = i*2; }
+    void ?{}(S *s) { }
+//    void ^?{}(S *s ) { }
+    S s1; // error
+  }
+  S s2; // okay
+}
Index: doc/rob_thesis/examples/ctor/placement_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/placement_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/placement_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,51 @@
+struct memory_pool {
+  char * start;
+  char * cur;
+  size_t size;
+  char * free;
+};
+
+void ?{}(memory_pool * pool, size_t size) {
+  pool->[start, cur] = malloc(size);
+  pool->size = size;
+  printf("initializing memory pool with size %lu at location %p\n", pool->size, pool->start);
+}
+
+void ^?{}(memory_pool * pool) {
+  free(pool->start);
+}
+
+forall(dtype T | sized(T))
+T * allocate(memory_pool * pool, unsigned int array_size = 1) {
+  size_t size = sizeof(T) * array_size;
+  printf("allocating block of size %lu...", size);
+  if (pool->cur + size < pool->start + pool->size) {
+    T * x = (T*)pool->cur;
+    pool->cur += size;
+    printf("success!\n");
+    printf("next address is %p\n", pool->cur);
+    return x;
+  } else {
+    printf("failed!\n");
+    // fail to allocate
+    return 0;
+  }
+}
+
+struct A {
+  int x, y, z;
+};
+void ?{}(A * a) {
+  a->[x,y,z] = [123, 456, 789];
+}
+
+int main() {
+  memory_pool pool = { 1024 };
+
+  int * x = allocate(&pool);
+  A * a = allocate(&pool);
+  A * b = allocate(&pool, 1000);
+  a{};
+  printf("%p\n", x);
+  printf("%p %d %d %d\n", a, a->[x,y,z]);
+}
Index: doc/rob_thesis/examples/ctor/return_dtor.c
===================================================================
--- doc/rob_thesis/examples/ctor/return_dtor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/return_dtor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,20 @@
+struct A;
+void ?{}(A *);
+void ^?{}(A *);
+
+void f(int i) {
+  A x;  // construct x
+  {
+    A y; // construct y
+    {
+      A z; // construct z
+      {
+        if (i == 0) return; // destruct x, y, z
+      }
+      if (i == 1) return; // destruct x, y, z
+      // destruct z
+    }
+    if (i == 2) return; // destruct x, y
+    // destruct y
+  }
+}
Index: doc/rob_thesis/examples/ctor/static_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/static_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/static_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,12 @@
+struct X {
+  int y, z;
+};
+void ?{}(X *);
+void ?{}(X *, int, int);
+void ^?{}(X *);
+
+int f(int x) {
+  static X a;
+  static X b = { x, x };
+  static X c = b;
+}
Index: doc/rob_thesis/examples/ctor/union_ctor.c
===================================================================
--- doc/rob_thesis/examples/ctor/union_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/ctor/union_ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,6 @@
+struct Y { int a; };
+struct Z { double z; };
+union X {
+  Y y;
+  Z z;
+};
Index: doc/rob_thesis/examples/intro/FileOutputStream.java
===================================================================
--- doc/rob_thesis/examples/intro/FileOutputStream.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/FileOutputStream.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,38 @@
+import java.io.IOException;
+import java.io.FileNotFoundException;
+
+public class FileOutputStream implements AutoCloseable {
+	public static int throwOnWrite;
+	public static int throwOnClose;
+	public static int throwOnOpen;
+
+	public static int numWrites;
+	public static int numCloses;
+	public static int numOpens;
+
+	private String filename;
+	private <EX extends Throwable> void doexcept(EX ex, boolean pred) throws EX {
+		if (pred) {
+			System.out.println("Stream: " + filename + " threw exception: " + ex);
+			throw ex;
+		}
+	}
+
+	public FileOutputStream(String filename) throws FileNotFoundException {
+		doexcept(new FileNotFoundException(), throwOnOpen == ++numOpens);
+		System.out.println("Opened file: " + filename);
+		this.filename = filename;
+	}
+	public void write(byte[] bytes) throws IOException {
+		doexcept(new IOException(), throwOnWrite == ++numWrites);
+		System.out.println("wrote message: " + new String(bytes) + " to file: " + filename);
+	}
+	public void close() throws IOException {
+		System.out.println("Closing file: " + filename);
+		filename = null;
+		doexcept(new IOException(), throwOnClose == ++numCloses);
+	}
+	protected void finalize() {
+		if (filename != null) System.out.println("Finalize closing file: " + filename);
+	}
+}
Index: doc/rob_thesis/examples/intro/compound_lit.c
===================================================================
--- doc/rob_thesis/examples/intro/compound_lit.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/compound_lit.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,16 @@
+int printf(const char *, ...);
+
+struct A { int x, y; };
+int f(struct A a, int z) {
+	printf("%d %d %d\n", a.x, a.y, z);
+}
+int g(int * x) {
+	if (x == 0) printf("NULL\n");
+	else printf("%d\n", *x);
+}
+
+int main() {
+	f((struct A){ 3, 4 }, (int){ 5 } = 10);
+	g((int[]){ 1, 2, 3 });
+	g(&(int){ 0 });
+}
Index: doc/rob_thesis/examples/intro/designation.c
===================================================================
--- doc/rob_thesis/examples/intro/designation.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/designation.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,24 @@
+int printf(const char *, ...);
+
+struct A {
+  int w, x, y, z;
+};
+
+void print(struct A a) {
+	printf("{ %d, %d, %d, %d }\n", a.w, a.x, a.y, a.z);
+}
+
+int main() {
+	struct A a0 = { .x=4, .z=1, .x=8 };
+	struct A a1 = { 1, .y=7, 6 };
+	struct A a2[3] = { [2]=a0, [0]=a1, { .z=3 } };
+
+	print(a0);
+	print(a1);
+	printf("{\n");
+	for (int i = 0; i < 3; i++) {
+		printf("  ");
+		print(a2[i]);
+	}
+	printf("}\n");
+}
Index: doc/rob_thesis/examples/intro/ignore.c
===================================================================
--- doc/rob_thesis/examples/intro/ignore.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/ignore.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,22 @@
+struct __ignore_t__ {
+};
+__ignore_t__ __ignore__;
+
+forall(dtype T | sized(T))
+__ignore_t__ ?=?(__ignore_t__ * dst, T src) {
+	return *dst;
+}
+
+forall(dtype T | sized(T) | { void ?{}(T *, T); })
+T ?=?(T * dst, __ignore_t__ src) {
+	return *dst;
+}
+
+int main() {
+	int x = 123, y = 456, z = 789;
+	double j = 3.14, i = 8.77;
+	[x, __ignore__, z] = [y, z, x];
+	[i, j, __ignore__] = [0, i, j];
+	printf("%d %d %d\n", x, y, z);
+	printf("%g %g\n", i, j);
+}
Index: doc/rob_thesis/examples/intro/ires.java
===================================================================
--- doc/rob_thesis/examples/intro/ires.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/ires.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,3 @@
+public interface ires {
+	public void write(String filename, String msg) throws Exception;
+}
Index: doc/rob_thesis/examples/intro/res.java
===================================================================
--- doc/rob_thesis/examples/intro/res.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/res.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,34 @@
+public class res {
+	private ires res;
+	public res(ires res) {
+		this.res = res;
+	}
+
+	public void dotest(String msg, int open, int write, int close) {
+		try {
+			System.out.println(msg);
+			FileOutputStream.throwOnOpen = open;
+			FileOutputStream.throwOnWrite = write;
+			FileOutputStream.throwOnClose = close;
+			res.write("foo.txt", "output message");
+		} catch (Exception ex) {
+		}
+		FileOutputStream.numOpens = 0;
+		FileOutputStream.numWrites = 0;
+		FileOutputStream.numCloses = 0;
+		System.gc();
+		System.runFinalization();
+		System.out.println();
+		System.out.flush();
+	}
+
+	public static void dotest(ires res) {
+		res r = new res(res);
+		r.dotest("Exception on open 1",  1, 0, 0);
+		r.dotest("Exception on open 2",  2, 0, 0);
+		r.dotest("Exception on write 1", 0, 1, 0);
+		r.dotest("Exception on write 2", 0, 2, 0);
+		r.dotest("Exception on close 1", 0, 0, 1);
+		r.dotest("Exception on close 2", 0, 0, 2);
+	}
+}
Index: doc/rob_thesis/examples/intro/res1.java
===================================================================
--- doc/rob_thesis/examples/intro/res1.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/res1.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,16 @@
+import java.io.IOException;
+
+public class res1 implements ires {
+	public void write(String filename, String msg) throws IOException {
+	  FileOutputStream out = new FileOutputStream(filename);  // may throw FileNotFoundException
+	  FileOutputStream log = new FileOutputStream("log.txt"); //  or SecurityException
+	  out.write(msg.getBytes()); // may throw an IOException
+	  log.write(msg.getBytes()); // may throw an IOException
+	  log.close(); // may throw an IOException
+	  out.close(); // may throw an IOException
+	}
+
+	public static void main(String[] args) {
+		res.dotest(new res1());
+	}
+}
Index: doc/rob_thesis/examples/intro/res2.java
===================================================================
--- doc/rob_thesis/examples/intro/res2.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/res2.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,22 @@
+import java.io.IOException;
+
+public class res2 implements ires {
+  public void write(String filename, String msg) throws Exception {
+    FileOutputStream out = new FileOutputStream(filename); // may throw FileNotFoundException
+    try {
+      FileOutputStream log = new FileOutputStream("log.txt"); //  or SecurityException
+      try {
+        out.write(msg.getBytes()); // may throw an IOException
+        log.write(msg.getBytes()); // may throw an IOException
+      } finally {
+        log.close(); // may throw an IOException
+      }
+    } finally {
+      out.close(); // may throw an IOException
+    }
+  }
+
+  public static void main(String[] args) {
+    res.dotest(new res2());
+  }
+}
Index: doc/rob_thesis/examples/intro/res3.java
===================================================================
--- doc/rob_thesis/examples/intro/res3.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/res3.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,17 @@
+import java.io.IOException;
+
+public class res3 implements ires {
+  public void write(String filename, String msg) throws Exception {
+    try (
+      FileOutputStream out = new FileOutputStream(filename); // may throw FileNotFoundException
+      FileOutputStream log = new FileOutputStream("log.txt"); //  or SecurityException
+    ) {
+      out.write(msg.getBytes()); // may throw an IOException
+      log.write(msg.getBytes()); // may throw an IOException
+    }
+  }
+
+  public static void main(String[] args) {
+    res.dotest(new res3());
+  }
+}
Index: doc/rob_thesis/examples/intro/tuple.cc
===================================================================
--- doc/rob_thesis/examples/intro/tuple.cc	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/tuple.cc	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,10 @@
+#include <iostream>
+#include <tuple>
+using namespace std;
+
+int main() {
+	tuple<int, int, int> triple(10, 20, 30);
+	cout << get<1>(triple) << endl;
+	tuple_element<2, tuple<int, float, double>>::type x = 3.14;
+	cout << tuple_size<decltype(triple)>::value << endl;
+}
Index: doc/rob_thesis/examples/intro/variadic.java
===================================================================
--- doc/rob_thesis/examples/intro/variadic.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/intro/variadic.java	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,25 @@
+class variadic {
+  int sum(int... args) {
+    int s = 0;
+    for (int x : args) {
+      s += x;
+    }
+    print(args.length, " ", args[0], " ", args[args.length-1], "\n");
+    return s;
+  }
+
+  void print(Object... objs) {
+    for (Object obj : objs) {
+      System.out.print(obj);
+    }
+  }
+
+  public void run() {
+    print("The sum from 1 to 10 is ", sum(1,2,3,4,5,6,7,8,9,10), ".\n");
+    print(sum(new int[]{1, 2,3}), "\n");
+  }
+
+  public static void main(String args[]) {
+    new variadic().run();
+  }
+}
Index: doc/rob_thesis/examples/scope_guard.h
===================================================================
--- doc/rob_thesis/examples/scope_guard.h	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/scope_guard.h	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,29 @@
+#ifndef SCOPE_GUARD_H
+#define SCOPE_GUARD_H
+
+struct ScopeGuard {
+  void (*fn)(void *);
+  // Args args;
+};
+
+// forall(ttype Args, ttype Ret)
+// void ?{}(ScopeGuard(Args, Ret) * this) {
+void ?{}(ScopeGuard * this) {
+
+}
+
+// // inline
+// forall(ttype Args, ttype Ret)
+// void ?{}(ScopeGuard(Args, Ret) * this, Ret (*fn)(Args), Args args) {
+//   this->fn = fn;
+//   // this->args = args;
+// }
+
+// inline
+// forall(ttype Args, ttype Ret)
+// void ^?{}(ScopeGuard(Args, Ret) * this) {
+void ^?{}(ScopeGuard * this) {
+  this->fn(0);
+}
+
+#endif
Index: doc/rob_thesis/examples/test_scoped_guard.c
===================================================================
--- doc/rob_thesis/examples/test_scoped_guard.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/test_scoped_guard.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,12 @@
+#include "scope_guard.h"
+
+extern "C" {
+  void free(void *);
+}
+
+int main() {
+  int * x = malloc(sizeof(10));
+  // ScopeGuard(int*, void) foo;
+  ScopeGuard foo;
+  foo.fn = free;
+}
Index: doc/rob_thesis/examples/tuples/assign.c
===================================================================
--- doc/rob_thesis/examples/tuples/assign.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/assign.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,9 @@
+int x, z;
+double y;
+[double, double] f();
+
+int main () {
+  [x, y, z] = [f(), 3];       // multiple assignment
+  // [x, y, z] = 1.5;            // mass assignment
+}
+
Index: doc/rob_thesis/examples/tuples/cast.c
===================================================================
--- doc/rob_thesis/examples/tuples/cast.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/cast.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,10 @@
+[int, int, int] f();
+[int, [int, int], int] g();
+
+int main() {
+  ([int, double])f();           // (1)
+  ([int, [int], int])g();         // (2)
+  printf("%d %d\n", ([void, [int, int]])g());      // (3) -- should work and doesn't -- tries to construct void object, but should ignore that component in terms of the type of the tuple
+  // ([int, int, int, int])g();    // (4) -- should not work and doesn't
+  // ([int, [int, int, int]])g();  // (5) -- should not work and doesn't
+}
Index: doc/rob_thesis/examples/tuples/ctor.c
===================================================================
--- doc/rob_thesis/examples/tuples/ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/ctor.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,10 @@
+struct S { int x; double y; };
+[void] ?{}(* [int, double] this, S s) {
+  this->0 = s.x;
+  this->1 = s.y;
+}
+int main() {
+  S s = { 123, 345 };
+  [int, double] x = s;
+  printf("%d %g\n", x);
+}
Index: doc/rob_thesis/examples/tuples/mrv.c
===================================================================
--- doc/rob_thesis/examples/tuples/mrv.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/mrv.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,2 @@
+[int, int] foo();
+[double, int] bar();
Index: doc/rob_thesis/examples/tuples/mrv_1.c
===================================================================
--- doc/rob_thesis/examples/tuples/mrv_1.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/mrv_1.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,34 @@
+#include <stdio.h>
+#include <ctype.h>
+struct mf_ret {
+  int freq;
+  char ch;
+};
+
+struct mf_ret most_frequent(const char * str) {
+  char freqs [26] = { 0 };
+  struct mf_ret ret = { 0, 'a' };
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret.freq) {  // update on new max
+        ret.freq = freqs[idx];
+        ret.ch = ch;
+      }
+    }
+  }
+  return ret;
+}
+
+void dothing(const char * str) {
+  struct mf_ret ret = most_frequent(str);
+  printf("%s -- %d %c\n", str, ret.freq, ret.ch);
+}
+
+int main() {
+  dothing("hello");
+  dothing("hello, world!");
+  dothing("aaabbbba");
+  dothing("");
+}
Index: doc/rob_thesis/examples/tuples/mrv_2.c
===================================================================
--- doc/rob_thesis/examples/tuples/mrv_2.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/mrv_2.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,31 @@
+#include <stdio.h>
+#include <ctype.h>
+
+int most_frequent(const char * str, char * ret_ch) {
+  char freqs [26] = { 0 };
+  int ret_freq = 0;
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret_freq) {  // update on new max
+        ret_freq = freqs[idx];
+        *ret_ch = ch;
+      }
+    }
+  }
+  return ret_freq;
+}
+
+void dothing(const char * str) {
+  char ch;
+  int freq = most_frequent(str, &ch);
+  printf("%s -- %d %c\n", str, freq, ch);
+}
+
+int main() {
+  dothing("hello");
+  dothing("hello, world!");
+  dothing("aaabbbba");
+  dothing("");
+}
Index: doc/rob_thesis/examples/tuples/mrv_3.c
===================================================================
--- doc/rob_thesis/examples/tuples/mrv_3.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/tuples/mrv_3.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,33 @@
+#include <stdio.h>
+#include <ctype.h>
+
+[int, char] most_frequent(const char * str) {
+  char freqs [26] = { 0 };
+  int ret_freq = 0;
+  char ret_ch = 'a';
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret_freq) {  // update on new max
+        ret_freq = freqs[idx];
+        ret_ch = ch;
+      }
+    }
+  }
+  return [ret_freq, ret_ch];
+}
+
+void dothing(const char * str) {
+  int freq;
+  char ch;
+  [freq, ch] = most_frequent(str);
+  printf("%s -- %d %c\n", str, ret_freq, ret_ch);
+}
+
+int main() {
+  dothing("hello");
+  dothing("hello, world!");
+  dothing("aaabbbba");
+  dothing("");
+}
Index: doc/rob_thesis/examples/variadic/new.c
===================================================================
--- doc/rob_thesis/examples/variadic/new.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/variadic/new.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,13 @@
+forall(dtype T | sized(T)) T * malloc(void);
+
+forall(dtype T, ttype Params | sized(T) | { void ?{}(T *, Params); })
+T * new(Params p) {
+  return ((T*)malloc()){ p }; // construct result of malloc
+}
+
+struct S { int x, y; }; 
+void ?{}(S *, int, int);
+
+int main() {
+  S * s = new(3, 4);
+}
Index: doc/rob_thesis/examples/variadic/print.c
===================================================================
--- doc/rob_thesis/examples/variadic/print.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/examples/variadic/print.c	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,11 @@
+forall(otype T, ttype Params |
+  { void print(T); void print(Params); })
+void print(T arg, Params rest) {
+  print(arg);
+  print(rest);
+}
+void print(const char * x) { printf("%s", x); }
+void print(int x) { printf("%d", x);  }
+int main() {
+  print("x = ", 123, ".");
+}
Index: doc/rob_thesis/intro.tex
===================================================================
--- doc/rob_thesis/intro.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/intro.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,673 @@
+%======================================================================
+\chapter{Introduction}
+%======================================================================
+
+\section{\CFA Background}
+\label{s:background}
+\CFA is a modern extension to the C programming language.
+As it is an extension of C, there is already a wealth of existing C code and principles that govern the design of the language.
+Among the goals set out in the original design of \CFA, four points stand out \cite{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}
+Therefore, these design principles must be kept in mind throughout the design and development of new language features.
+In order to appeal to existing C programmers, great care must be taken to ensure that new features naturally feel like C.
+The remainder of this section describes some of the important new features that currently exist in \CFA, to give the reader the necessary context in which the new features presented in this thesis must dovetail. % TODO: harmonize with?
+
+\subsection{C Background}
+\label{sub:c_background}
+One of the lesser-known features of standard C is \emph{designations}.
+Designations are similar to named parameters in languages such as Python and Scala, except that they only apply to aggregate initializers.
+\begin{cfacode}
+struct A {
+  int w, x, y, z;
+};
+A a0 = { .x:4 .z:1, .x:8 };
+A a1 = { 1, .y:7, 6 };
+A a2[4] = { [2]:a0, [0]:a1, { .z:3 } };
+// equvialent to
+// A a0 = { 0, 8, 0, 1 };
+// A a1 = { 1, 0, 7, 6 };
+// A a2[4] = { a1, { 0, 0, 0, 3 }, a0, { 0, 0, 0, 0 } };
+\end{cfacode}
+Designations allow specifying the field to initialize by name, rather than by position.
+Any field not explicitly initialized is initialized as if it had static storage duration \cite[p.~141]{C11}.
+A designator specifies the current object for initialization, and as such any undesignated subobjects pick up where the last initialization left off.
+For example, in the initialization of @a1@, the initializer of @y@ is @7@, and the unnamed initializer @6@ initializes the next subobject, @z@.
+Later initializers override earlier initializers, so a subobject for which there is more than one initializer is only initailized by its last initializer.
+This can be seen in the initialization of @a0@, where @x@ is designated twice, and thus initialized to @8@.
+Note that in \CFA, designations use a colon separator, rather than an equals sign as in C.
+
+C also provides \emph{compound literal} expressions, which provide a first-class mechanism for creating unnamed objects.
+\begin{cfacode}
+struct A { int x, y; };
+int f(A, int);
+int g(int *);
+
+f((A){ 3, 4 }, (int){ 5 } = 10);
+g((int[]){ 1, 2, 3 });
+g(&(int){ 0 });
+\end{cfacode}
+Compound literals create an unnamed object, and result in an lvalue, so it is legal to assign a value into a compound literal or to take its address \cite[p.~86]{C11}.
+Syntactically, compound literals look like a cast operator followed by a brace-enclosed initializer, but semantically are different from a C cast, which only applies basic conversions and is never an lvalue.
+
+\subsection{Overloading}
+\label{sub:overloading}
+Overloading is the ability to specify multiple entities with the same name.
+The most common form of overloading is function overloading, wherein multiple functions can be defined with the same name, but with different signatures.
+Like in \CC, \CFA allows overloading based both on the number of parameters and on the types of parameters.
+  \begin{cfacode}
+  void f(void);  // (1)
+  void f(int);   // (2)
+  void f(char);  // (3)
+
+  f('A');        // selects (3)
+  \end{cfacode}
+In this case, there are three @f@ procedures, where @f@ takes either 0 or 1 arguments, and if an argument is provided then it may be of type @int@ or of type @char@.
+Exactly which procedure is executed depends on the number and types of arguments passed.
+If there is no exact match available, \CFA attempts to find a suitable match by examining the C built-in conversion heuristics.
+  \begin{cfacode}
+  void g(long long);
+
+  g(12345);
+  \end{cfacode}
+In the above example, there is only one instance of @g@, which expects a single parameter of type @long long@.
+Here, the argument provided has type @int@, but since all possible values of type @int@ can be represented by a value of type @long long@, there is a safe conversion from @int@ to @long long@, and so \CFA calls the provided @g@ routine.
+
+In addition to this form of overloading, \CFA also allows overloading based on the number and types of \emph{return} values.
+This extension is a feature that is not available in \CC, but is available in other programming languages such as Ada \cite{Ada95}.
+  \begin{cfacode}
+  int g();         // (1)
+  double g();      // (2)
+
+  int x = g();     // selects (1)
+  \end{cfacode}
+Here, the only difference between the signatures of the different versions of @g@ is in the return values.
+The result context is used to select an appropriate routine definition.
+In this case, the result of @g@ is assigned into a variable of type @int@, so \CFA prefers the routine that returns a single @int@, because it is an exact match.
+
+There are times when a function should logically return multiple values.
+Since a function in standard C can only return a single value, a programmer must either take in additional return values by address, or the function's designer must create a wrapper structure t0 package multiple return-values.
+\begin{cfacode}
+int f(int * ret) {        // returns a value through parameter ret
+  *ret = 37;
+  return 123;
+}
+
+int res1, res2;           // allocate return value
+int res1 = g(&res2);      // explicitly pass storage
+\end{cfacode}
+The former solution is awkward because it requires the caller to explicitly allocate memory for $n$ result variables, even if they are only temporary values used as a subexpression, or even not used at all.
+\begin{cfacode}
+struct A {
+  int x, y;
+};
+struct A g() {            // returns values through a structure
+  return (struct A) { 123, 37 };
+}
+struct A res3 = g();
+... res3.x ... res3.y ... // use result values
+\end{cfacode}
+The latter approach requires the caller to either learn the field names of the structure or learn the names of helper routines to access the individual return values.
+Both solutions are syntactically unnatural.
+
+In \CFA, it is possible to directly declare a function returning mutliple values.
+This provides important semantic information to the caller, since return values are only for output.
+\begin{cfacode}
+[int, int] f() {       // don't need to create a new type
+  return [123, 37];
+}
+\end{cfacode}
+However, the ability to return multiple values requires a syntax for accepting the results from a function.
+In standard C, return values are most commonly assigned directly into local variables, or are used as the arguments to another function call.
+\CFA allows both of these contexts to accept multiple return values.
+\begin{cfacode}
+int res1, res2;
+[res1, res2] = f();    // assign return values into local variables
+
+void g(int, int);
+g(f());                // pass both return values of f to g
+\end{cfacode}
+As seen in the example, it is possible to assign the results from a return value directly into local variables.
+These local variables can be referenced naturally, without requiring any unpacking as in structured return values.
+Perhaps more interesting is the fact that multiple return values can be passed to multiple parameters seamlessly, as in the call @g(f())@.
+In this call, the return values from @f@ are linked to the parameters of @g@ so that each of the return values is passed directly to the corresponding parameter of @g@, without any explicit storing, unpacking, or additional naming.
+
+An extra quirk introduced by multiple return values is in the resolution of function calls.
+  \begin{cfacode}
+  int f();            // (1)
+  [int, int] f();     // (2)
+
+  void g(int, int);
+
+  int x, y;
+  [x, y] = f();       // selects (2)
+  g(f());             // selects (2)
+  \end{cfacode}
+In this example, the only possible call to @f@ that can produce the two @int@s required by @g@ is the second option.
+A similar reasoning holds for assigning into multiple variables.
+
+In \CFA, overloading also applies to operator names, known as \emph{operator overloading}.
+Similar to function overloading, a single operator is given multiple meanings by defining new versions of the operator with different signatures.
+In \CC, this can be done as follows
+  \begin{cppcode}
+  struct A { int i; };
+  int operator+(A x, A y);
+  bool operator<(A x, A y);
+  \end{cppcode}
+
+In \CFA, the same example can be written as follows.
+  \begin{cfacode}
+  struct A { int i; };
+  int ?+?(A x, A y);
+  bool ?<?(A x, A y);
+  \end{cfacode}
+Notably, the only difference in this example is syntax.
+Most of the operators supported by \CC for operator overloading are also supported in \CFA.
+Of notable exception are the logical operators (e.g. @||@), the sequence operator (i.e. @,@), and the member-access operators (e.g. @.@ and \lstinline{->}).
+
+Finally, \CFA also permits overloading variable identifiers.
+This feature is not available in \CC.
+  \begin{cfacode} % TODO: pick something better than x? max, zero, one?
+  struct Rational { int numer, denom; };
+  int x = 3;               // (1)
+  double x = 1.27;         // (2)
+  Rational x = { 4, 11 };  // (3)
+
+  void g(double);
+
+  x += 1;                  // chooses (1)
+  g(x);                    // chooses (2)
+  Rational y = x;          // chooses (3)
+  \end{cfacode}
+In this example, there are three definitions of the variable @x@.
+Based on the context, \CFA attempts to choose the variable whose type best matches the expression context.
+
+Finally, the values @0@ and @1@ have special status in standard C.
+In particular, the value @0@ is both an integer and a pointer literal, and thus its meaning depends on the context.
+In addition, several operations can be redefined in terms of other operations and the values @0@ and @1@.
+For example,
+\begin{cfacode}
+int x;
+if (x) {  // if (x != 0)
+  x++;    //   x += 1;
+}
+\end{cfacode}
+Every if statement in C compares the condition with @0@, and every increment and decrement operator is semantically equivalent to adding or subtracting the value @1@ and storing the result.
+Due to these rewrite rules, the values @0@ and @1@ have the types \zero and \one in \CFA, which allow for overloading various operations that connect to @0@ and @1@ \footnote{In the original design of \CFA, @0@ and @1@ were overloadable names \cite[p.~7]{cforall}.}.
+The types \zero and \one have special built in implicit conversions to the various integral types, and a conversion to pointer types for @0@, which allows standard C code involving @0@ and @1@ to work as normal.
+  \begin{cfacode}
+  // lvalue is similar to returning a reference in C++
+  lvalue Rational ?+=?(Rational *a, Rational b);
+  Rational ?=?(Rational * dst, zero_t) {
+    return *dst = (Rational){ 0, 1 };
+  }
+
+  Rational sum(Rational *arr, int n) {
+    Rational r;
+    r = 0;     // use rational-zero_t assignment
+    for (; n > 0; n--) {
+      r += arr[n-1];
+    }
+    return r;
+  }
+  \end{cfacode}
+This function takes an array of @Rational@ objects and produces the @Rational@ representing the sum of the array.
+Note the use of an overloaded assignment operator to set an object of type @Rational@ to an appropriate @0@ value.
+
+\subsection{Polymorphism}
+\label{sub:polymorphism}
+In its most basic form, polymorphism grants the ability to write a single block of code that accepts different types.
+In particular, \CFA supports the notion of parametric polymorphism.
+Parametric polymorphism allows a function to be written generically, for all values of all types, without regard to the specifics of a particular type.
+For example, in \CC, the simple identity function for all types can be written as
+  \begin{cppcode}
+  template<typename T>
+  T identity(T x) { return x; }
+  \end{cppcode}
+\CC uses the template mechanism to support parametric polymorphism. In \CFA, an equivalent function can be written as
+  \begin{cfacode}
+  forall(otype T)
+  T identity(T x) { return x; }
+  \end{cfacode}
+Once again, the only visible difference in this example is syntactic.
+Fundamental differences can be seen by examining more interesting examples.
+In \CC, a generic sum function is written as follows
+  \begin{cppcode}
+  template<typename T>
+  T sum(T *arr, int n) {
+    T t;
+    for (; n > 0; n--) t += arr[n-1];
+    return t;
+  }
+  \end{cppcode}
+Here, the code assumes the existence of a default constructor, assignment operator, and an addition operator over the provided type @T@.
+If any of these required operators are not available, the \CC compiler produces an error message stating which operators could not be found.
+
+A similar sum function can be written in \CFA as follows
+  \begin{cfacode}
+  forall(otype T | **R**{ T ?=?(T *, zero_t); T ?+=?(T *, T); }**R**)
+  T sum(T *arr, int n) {
+    T t = 0;
+    for (; n > 0; n--) t = t += arr[n-1];
+    return t;
+  }
+  \end{cfacode}
+The first thing to note here is that immediately following the declaration of @otype T@ is a list of \emph{type assertions} that specify restrictions on acceptable choices of @T@.
+In particular, the assertions above specify that there must be a an assignment from \zero to @T@ and an addition assignment operator from @T@ to @T@.
+The existence of an assignment operator from @T@ to @T@ and the ability to create an object of type @T@ are assumed implicitly by declaring @T@ with the @otype@ type-class.
+In addition to @otype@, there are currently two other type-classes.
+The three type parameter kinds are summarized in \autoref{table:types}
+
+\begin{table}[h!]
+  \begin{center}
+    \begin{tabular}{|c||c|c|c||c|c|c|}
+                                                                                                    \hline
+    name    & object type & incomplete type & function type & can assign value & can create & has size \\ \hline
+    @otype@ & X           &                 &               & X                & X          & X        \\ \hline
+    @dtype@ & X           & X               &               &                  &            &          \\ \hline
+    @ftype@ &             &                 & X             &                  &            &          \\ \hline
+    \end{tabular}
+  \end{center}
+  \caption{\label{table:types} The different kinds of type parameters in \CFA}
+\end{table}
+
+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.
+In contrast, the explicit nature of assertions allows \CFA's polymorphic functions to be separately compiled.
+
+In \CFA, a set of assertions can be factored into a \emph{trait}.
+\begin{cfacode}
+  trait Addable(otype T) {
+    T ?+?(T, T);
+    T ++?(T);
+    T ?++(T);
+  }
+  forall(otype T | Addable(T)) void f(T);
+  forall(otype T | Addable(T) | { T --?(T); }) T g(T);
+  forall(otype T, U | Addable(T) | { T ?/?(T, U); }) U h(T, U);
+\end{cfacode}
+This capability allows specifying the same set of assertions in multiple locations, without the repetition and likelihood of mistakes that come with manually writing them out for each function declaration.
+
+\section{Invariants}
+% TODO: discuss software engineering benefits of ctor/dtors: {pre/post} conditions, invariants
+% an important invariant is the state of the environment (memory, resources)
+% some objects pass their contract to the object user
+An \emph{invariant} is a logical assertion that true for some duration of a program's execution.
+Invariants help a programmer to reason about code correctness and prove properties of programs.
+
+In object-oriented programming languages, type invariants are typically established in a constructor and maintained throughout the object's lifetime.
+This is typically achieved through a combination of access control modifiers and a restricted interface.
+Typically, data which requires the maintenance of an invariant is hidden from external sources using the \emph{private} modifier, which restricts reads and writes to a select set of trusted routines, including member functions.
+It is these trusted routines that perform all modifications to internal data in a way that is consistent with the invariant, by ensuring that the invariant holds true at the end of the routine call.
+
+In C, the @assert@ macro is often used to ensure invariants are true.
+Using @assert@, the programmer can check a condition and abort execution if the condition is not true.
+This is a powerful tool that forces the programmer to deal with logical inconsistencies as they occur.
+For production, assertions can be removed by simply defining the preprocessor macro @NDEBUG@, making it simple to ensure that assertions are 0-cost for a performance intensive application.
+\begin{cfacode}
+struct Rational {
+  int n, d;
+};
+struct Rational create_rational(int n, int d) {
+  assert(d != 0);  // precondition
+  if (d < 0) {
+    n *= -1;
+    d *= -1;
+  }
+  assert(d > 0);  // postcondition
+  // rational invariant: d > 0
+  return (struct Rational) { n, d };
+}
+struct Rational rat_abs(struct Rational r) {
+  assert(r.d > 0); // check invariant, since no access control
+  r.n = abs(r.n);
+  assert(r.d > 0); // ensure function preserves invariant on return value
+  return r;
+}
+\end{cfacode}
+
+Some languages, such as D, provide language-level support for specifying program invariants.
+In addition to providing a C-like @assert@ expression, D allows specifying type invariants that are automatically checked at the end of a constructor, beginning of a destructor, and at the beginning and end of every public member function.
+\begin{dcode}
+import std.math;
+struct Rational {
+  invariant {
+    assert(d > 0, "d <= 0");
+  }
+  int n, d;
+  this(int n, int d) {  // constructor
+    assert(d != 0);
+    this.n = n;
+    this.d = d;
+    // implicitly check invariant
+  }
+  Rational abs() {
+    // implicitly check invariant
+    return Rational(std.math.abs(n), d);
+    // implicitly check invariant
+  }
+}
+\end{dcode}
+The D compiler is able to assume that assertions and invariants hold true and perform optimizations based on those assumptions.
+
+An important invariant is the state of the execution environment, including the heap, the open file table, the state of global variables, etc.
+Since resources are finite, it is important to ensure that objects clean up properly when they are finished, restoring the execution environment to a stable state so that new objects can reuse resources.
+
+\section{Resource Management}
+\label{s:ResMgmt}
+
+Resource management is a problem that pervades every programming language.
+
+In standard C, resource management is largely a manual effort on the part of the programmer, with a notable exception to this rule being the program stack.
+The program stack grows and shrinks automatically with each function call, as needed for local variables.
+However, whenever a program needs a variable to outlive the block it is created in, the storage must be allocated dynamically with @malloc@ and later released with @free@.
+This pattern is extended to more complex objects, such as files and sockets, which also outlive the block where they are created, but at their core is resource management.
+Once allocated storage escapes a block, the responsibility for deallocating the storage is not specified in a function's type, that is, that the return value is owned by the caller.
+This implicit convention is provided only through documentation about the expectations of functions.
+
+In other languages, a hybrid situation exists where resources escape the allocation block, but ownership is precisely controlled by the language.
+This pattern requires a strict interface and protocol for a data structure, where the protocol consists of a pre-initialization and a post-termination call, and all intervening access is done via interface routines.
+This kind of encapsulation is popular in object-oriented programming languages, and like the stack, it contains a significant portion of resource management cases.
+
+For example, \CC directly supports this pattern through class types and an idiom known as RAII \footnote{Resource Acquisition is Initialization} by means of constructors and destructors.
+Constructors and destructors are special routines that are automatically inserted into the appropriate locations to bookend the lifetime of an object.
+Constructors allow the designer of a type to establish invariants for objects of that type, since it is guaranteed that every object must be initialized through a constructor.
+In particular, constructors allow a programmer to ensure that all objects are initially set to a valid state.
+On the other hand, destructors provide a simple mechanism for tearing down an object and resetting the environment in which the object lived.
+RAII ensures that if all resources are acquired in a constructor and released in a destructor, there are no resource leaks, even in exceptional circumstances.
+A type with at least one non-trivial constructor or destructor will henceforth be referred to as a \emph{managed type}.
+In the context of \CFA, a non-trivial constructor is either a user defined constructor or an auto generated constructor that calls a non-trivial constructor.
+
+For the remaining resource ownership cases, programmer must follow a brittle, explicit protocol for freeing resources or an implicit porotocol implemented via the programming language.
+
+In garbage collected languages, such as Java, resources are largely managed by the garbage collector.
+Still, garbage collectors are typically focus only on memory management.
+There are many kinds of resources that the garbage collector does not understand, such as sockets, open files, and database connections.
+In particular, Java supports \emph{finalizers}, which are similar to destructors.
+Sadly, finalizers come with far fewer guarantees, to the point where a completely conforming JVM may never call a single finalizer. % TODO: citation JVM spec; http://stackoverflow.com/a/2506514/2386739
+Due to operating system resource limits, this is unacceptable for many long running tasks. % TODO: citation?
+Instead, the paradigm in Java requires programmers manually keep track of all resource \emph{except} memory, leading many novices and experts alike to forget to close files, etc.
+Complicating the picture, uncaught exceptions can cause control flow to change dramatically, leaking a resource which appears on first glance to be closed.
+\begin{javacode}
+void write(String filename, String msg) throws Exception {
+  FileOutputStream out = new FileOutputStream(filename);
+  FileOutputStream log = new FileOutputStream(filename);
+  out.write(msg.getBytes());
+  log.write(msg.getBytes());
+  log.close();
+  out.close();
+}
+\end{javacode}
+Any line in this program can throw an exception.
+This leads to a profusion of finally blocks around many function bodies, since it isn't always clear when an exception may be thrown.
+\begin{javacode}
+public void write(String filename, String msg) throws Exception {
+  FileOutputStream out = new FileOutputStream(filename);
+  try {
+    FileOutputStream log = new FileOutputStream("log.txt");
+    try {
+      out.write(msg.getBytes());
+      log.write(msg.getBytes());
+    } finally {
+      log.close();
+    }
+  } finally {
+    out.close();
+  }
+}
+\end{javacode}
+In Java 7, a new \emph{try-with-resources} construct was added to alleviate most of the pain of working with resources, but ultimately it still places the burden squarely on the user rather than on the library designer.
+Furthermore, for complete safety this pattern requires nested objects to be declared separately, otherwise resources which can throw an exception on close can leak nested resources. % TODO: cite oracle article http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html?
+\begin{javacode}
+public void write(String filename, String msg) throws Exception {
+  try (
+    FileOutputStream out = new FileOutputStream(filename);
+    FileOutputStream log = new FileOutputStream("log.txt");
+  ) {
+    out.write(msg.getBytes());
+    log.write(msg.getBytes());
+  } // automatically closes out and log in every exceptional situation
+}
+\end{javacode}
+On the other hand, the Java compiler generates more code if more resources are declared, meaning that users must be more familiar with each type and library designers must provide better documentation.
+
+% D has constructors and destructors that are worth a mention (under classes) https://dlang.org/spec/spec.html
+%  also https://dlang.org/spec/struct.html#struct-constructor
+% these are declared in the struct, so they're closer to C++ than to CFA, at least syntactically. Also do not allow for default constructors
+% D has a GC, which already makes the situation quite different from C/C++
+The programming language, D, also manages resources with constructors and destructors \cite{D}.
+In D, @struct@s are stack allocated and managed via scoping like in \CC, whereas @class@es are managed automatically by the garbage collector.
+Like Java, using the garbage collector means that destructors may never be called, requiring the use of finally statements to ensure dynamically allocated resources that are not managed by the garbage collector, such as open files, are cleaned up.
+Since D supports RAII, it is possible to use the same techniques as in \CC to ensure that resources are released in a timely manner.
+Finally, D provides a scope guard statement, which allows an arbitrary statement to be executed at normal scope exit with \emph{success}, at exceptional scope exit with \emph{failure}, or at normal and exceptional scope exit with \emph{exit}. % cite? https://dlang.org/spec/statement.html#ScopeGuardStatement
+It has been shown that the \emph{exit} form of the scope guard statement can be implemented in a library in \CC. % cite: http://www.drdobbs.com/184403758
+
+% TODO: discussion of lexical scope vs. dynamic
+% see Peter's suggestions
+% RAII works in both cases. Guaranteed to work in stack case, works in heap case if root is deleted (but it's dangerous to rely on this, because of exceptions)
+
+\section{Tuples}
+\label{s:Tuples}
+In mathematics, tuples are finite-length sequences which, unlike sets, allow duplicate elements.
+In programming languages, tuples are a construct that provide fixed-sized heterogeneous lists of elements.
+Many programming languages have tuple constructs, such as SETL, \KWC, ML, and Scala.
+
+\KWC, a predecessor of \CFA, introduced tuples to C as an extension of the C syntax, rather than as a full-blown data type \cite{Till89}.
+In particular, Till noted that C already contains a tuple context in the form of function parameter lists.
+The main contributions of that work were in the form of adding tuple contexts to assignment in the form of multiple assignment and mass assignment (discussed in detail in section \ref{s:TupleAssignment}), function return values (see section \ref{s:MRV_Functions}), and record field access (see section \ref{s:MemberAccessTuple}).
+Adding tuples to \CFA has previously been explored by Esteves \cite{Esteves04}.
+
+The design of tuples in \KWC took much of its inspiration from SETL.
+SETL is a high-level mathematical programming language, with tuples being one of the primary data types.
+Tuples in SETL allow a number of operations, including subscripting, dynamic expansion, and multiple assignment.
+
+\CCeleven introduced @std::tuple@ as a library variadic template struct.
+Tuples are a generalization of @std::pair@, in that they allow for arbitrary length, fixed-size aggregation of heterogeneous values.
+\begin{cppcode}
+tuple<int, int, int> triple(10, 20, 30);
+get<1>(triple); // access component 1 => 30
+
+tuple<int, double> f();
+int i;
+double d;
+tie(i, d) = f(); // assign fields of return value into local variables
+
+tuple<int, int, int> greater(11, 0, 0);
+triple < greater; // true
+\end{cppcode}
+Tuples are simple data structures with few specific operations.
+In particular, it is possible to access a component of a tuple using @std::get<N>@.
+Another interesting feature is @std::tie@, which creates a tuple of references, which allows assigning the results of a tuple-returning function into separate local variables, without requiring a temporary variable.
+Tuples also support lexicographic comparisons, making it simple to write aggregate comparators using @std::tie@.
+
+There is a proposal for \CCseventeen called \emph{structured bindings}, that introduces new syntax to eliminate the need to pre-declare variables and use @std::tie@ for binding the results from a function call. % TODO: cite http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0144r0.pdf
+\begin{cppcode}
+tuple<int, double> f();
+auto [i, d] = f(); // unpacks into new variables i, d
+
+tuple<int, int, int> triple(10, 20, 30);
+auto & [t1, t2, t3] = triple;
+t2 = 0; // changes triple
+
+struct S { int x; double y; };
+S s = { 10, 22.5 };
+auto [x, y] = s; // unpack s
+\end{cppcode}
+Structured bindings allow unpacking any struct with all public non-static data members into fresh local variables.
+The use of @&@ allows declaring new variables as references, which is something that cannot be done with @std::tie@, since \CC references do not support rebinding.
+This extension requires the use of @auto@ to infer the types of the new variables, so complicated expressions with a non-obvious type must documented with some other mechanism.
+Furthermore, structured bindings are not a full replacement for @std::tie@, as it always declares new variables.
+
+Like \CC, D provides tuples through a library variadic template struct.
+In D, it is possible to name the fields of a tuple type, which creates a distinct type.
+\begin{dcode} % TODO: cite http://dlang.org/phobos/std_typecons.html
+Tuple!(float, "x", float, "y") point2D;
+Tuple!(float, float) float2;  // different types
+
+point2D[0]; // access first element
+point2D.x;  // access first element
+
+float f(float x, float y) {
+  return x+y;
+}
+
+f(point2D.expand);
+\end{dcode}
+Tuples are 0-indexed and can be subscripted using an integer or field name, if applicable.
+The @expand@ method produces the components of the tuple as a list of separate values, making it possible to call a function that takes $N$ arguments using a tuple with $N$ components.
+
+Tuples are a fundamental abstraction in most functional programming languages, such as Standard ML.
+A function in SML always accepts exactly one argument.
+There are two ways to mimic multiple argument functions: the first through currying and the second by accepting tuple arguments.
+\begin{smlcode}
+fun fact (n : int) =
+  if (n = 0) then 1
+  else n*fact(n-1)
+
+fun binco (n: int, k: int) =
+  real (fact n) / real (fact k * fact (n-k))
+\end{smlcode}
+Here, the function @binco@ appears to take 2 arguments, but it actually takes a single argument which is implicitly decomposed via pattern matching.
+Tuples are a foundational tool in SML, allowing the creation of arbitrarily complex structured data types.
+
+Scala, like \CC, provides tuple types through the standard library.
+Scala provides tuples of size 1 through 22 inclusive through generic data structures.
+Tuples support named access and subscript access, among a few other operations.
+\begin{scalacode}
+val a = new Tuple3[Int, String, Double](0, "Text", 2.1)  // explicit creation
+val b = (6, 'a', 1.1f)       // syntactic sugar for Tuple3[Int, Char, Float]
+val (i, _, d) = triple       // extractor syntax, ignore middle element
+
+println(a._2)                // named access => print "Text"
+println(b.productElement(0)) // subscript access => print 6
+\end{scalacode}
+In Scala, tuples are primarily used as simple data structures for carrying around multiple values or for returning multiple values from a function.
+The 22-element restriction is an odd and arbitrary choice, but in practice it doesn't cause problems since large tuples are uncommon.
+Subscript access is provided through the @productElement@ method, which returns a value of the top-type @Any@, since it is impossible to receive a more precise type from a general subscripting method due to type erasure.
+The disparity between named access beginning at @_1@ and subscript access starting at @0@ is likewise an oddity, but subscript access is typically avoided since it discards type information.
+Due to the language's pattern matching facilities, it is possible to extract the values from a tuple into named variables, which is a more idiomatic way of accessing the components of a tuple.
+
+
+\Csharp has similarly strange limitations, allowing tuples of size up to 7 components. % TODO: cite https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
+The officially supported workaround for this shortcoming is to nest tuples in the 8th component.
+\Csharp allows accessing a component of a tuple by using the field @Item$N$@ for components 1 through 7, and @Rest@ for the nested tuple.
+
+
+% TODO: cite 5.3 https://docs.python.org/3/tutorial/datastructures.html
+In Python, tuples are immutable sequences that provide packing and unpacking operations.
+While the tuple itself is immutable, and thus does not allow the assignment of components, there is nothing preventing a component from being internally mutable.
+The components of a tuple can be accessed by unpacking into multiple variables, indexing, or via field name, like D.
+Tuples support multiple assignment through a combination of packing and unpacking, in addition to the common sequence operations.
+
+% TODO: cite https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/doc/uid/TP40014097-CH31-ID448
+Swift, like D, provides named tuples, with components accessed by name, index, or via extractors.
+Tuples are primarily used for returning multiple values from a function.
+In Swift, @Void@ is an alias for the empty tuple, and there are no single element tuples.
+
+\section{Variadic Functions}
+\label{sec:variadic_functions}
+In statically-typed programming languages, functions are typically defined to receive a fixed number of arguments of specified types.
+Variadic argument functions provide the ability to define a function that can receive a theoretically unbounded number of arguments.
+
+C provides a simple implementation of variadic functions.
+A function whose parameter list ends with @, ...@ is a variadic function.
+Among the most common variadic functions is @printf@.
+\begin{cfacode}
+int printf(const char * fmt, ...);
+printf("%d %g %c %s", 10, 3.5, 'X', "a string");
+\end{cfacode}
+Through the use of a format string, @printf@ allows C programmers to print any of the standard C data types.
+Still, @printf@ is extremely limited, since the format codes are specified by the C standard, meaning users cannot define their own format codes to extend @printf@ for new data types or new formatting rules.
+
+C provides manipulation of variadic arguments through the @va_list@ data type, which abstracts details of the manipulation of variadic arguments.
+Since the variadic arguments are untyped, it is up to the function to interpret any data that is passed in.
+Additionally, the interface to manipulate @va_list@ objects is essentially limited to advancing to the next argument, without any built-in facility to determine when the last argument is read.
+This requires the use of an \emph{argument descriptor} to pass information to the function about the structure of the argument list, including the number of arguments and their types.
+The format string in @printf@ is one such example of an argument descriptor.
+\begin{cfacode}
+int f(const char * fmt, ...) {
+  va_list args;
+  va_start(args, fmt);  // initialize va_list
+  for (const char * c = fmt; *c != '\0'; ++c) {
+    if (*c == '%') {
+      ++c;
+      switch (*c) {
+        case 'd': {
+          int i = va_arg(args, int);  // have to specify type
+          // ...
+          break;
+        }
+        case 'g': {
+          double d = va_arg(args, double);
+          // ...
+          break;
+        }
+        ...
+      }
+    }
+  }
+  va_end(args);
+  return ...;
+}
+\end{cfacode}
+Every case must be handled explicitly, since the @va_arg@ macro requires a type argument to determine how the next set of bytes is to be interpreted.
+Furthermore, if the user makes a mistake, compile-time checking is typically restricted to standard format codes and their corresponding types.
+In general, this means that C's variadic functions are not type-safe, making them difficult to use properly.
+
+% When arguments are passed to a variadic function, they undergo \emph{default argument promotions}.
+% Specifically, this means that
+
+\CCeleven added support for \emph{variadic templates}, which add much needed type-safety to C's variadic landscape.
+It is possible to use variadic templates to define variadic functions and variadic data types.
+\begin{cppcode}
+void print(int);
+void print(char);
+void print(double);
+...
+
+void f() {}    // base case
+
+template<typename T, typename... Args>
+void f(const T & arg, const Args &... rest) {
+  print(arg);  // print the current element
+  f(rest...);  // handle remaining arguments recursively
+}
+\end{cppcode}
+Variadic templates work largely through recursion on the \emph{parameter pack}, which is the argument with @...@ following its type.
+A parameter pack matches 0 or more elements, which can be types or expressions depending on the context.
+Like other templates, variadic template functions rely on an implicit set of constraints on a type, in this example a @print@ routine.
+That is, it is possible to use the @f@ routine any any type provided there is a corresponding @print@ routine, making variadic templates fully open to extension, unlike variadic functions in C.
+
+Recent \CC standards (\CCfourteen, \CCseventeen) expand on the basic premise by allowing variadic template variables and providing convenient expansion syntax to remove the need for recursion in some cases, amongst other things.
+
+% D has variadic templates that deserve a mention http://dlang.org/ctarguments.html
+
+In Java, a variadic function appears similar to a C variadic function in syntax.
+\begin{javacode}
+int sum(int... args) {
+  int s = 0;
+  for (int x : args) {
+    s += x;
+  }
+  return s;
+}
+
+void print(Object... objs) {
+  for (Object obj : objs) {
+    System.out.print(obj);
+  }
+}
+
+print("The sum from 1 to 10 is ", sum(1,2,3,4,5,6,7,8,9,10), ".\n");
+\end{javacode}
+The key difference is that Java variadic functions are type-safe, because they specify the type of the argument immediately prior to the ellipsis.
+In Java, variadic arguments are syntactic sugar for arrays, allowing access to length, subscripting operations, and for-each iteration on the variadic arguments, among other things.
+Since the argument type is specified explicitly, the top-type @Object@ can be used to accept arguments of any type, but to do anything interesting on the argument requires a down-cast to a more specific type, landing Java in a similar situation to C in that writing a function open to extension is difficult.
+
+The other option is to restrict the number of types that can be passed to the function by using a more specific type.
+Unfortunately, Java's use of nominal inheritance means that types must explicitly inherit from classes or interfaces in order to be considered a subclass.
+The combination of these two issues greatly restricts the usefulness of variadic functions in Java.
Index: doc/rob_thesis/thesis-frontpgs.tex
===================================================================
--- doc/rob_thesis/thesis-frontpgs.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/thesis-frontpgs.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,141 @@
+% T I T L E   P A G E
+% -------------------
+% Last updated May 24, 2011, by Stephen Carr, IST-Client Services
+% The title page is counted as page `i' but we need to suppress the
+% page number.  We also don't want any headers or footers.
+\pagestyle{empty}
+\pagenumbering{roman}
+
+% The contents of the title page are specified in the "titlepage"
+% environment.
+\begin{titlepage}
+        \begin{center}
+        \vspace*{1.0cm}
+
+        \Huge
+        {\bf Resource Management and Tuples in \CFA}
+
+        \vspace*{1.0cm}
+
+        \normalsize
+        by \\
+
+        \vspace*{1.0cm}
+
+        \Large
+        Rob Schluntz \\
+
+        \vspace*{3.0cm}
+
+        \normalsize
+        A thesis \\
+        presented to the University of Waterloo \\
+        in fulfillment of the \\
+        thesis requirement for the degree of \\
+        Master of Mathematics \\
+        in \\
+        Computer Science \\
+
+        \vspace*{2.0cm}
+
+        Waterloo, Ontario, Canada, 2017 \\
+
+        \vspace*{1.0cm}
+
+        \copyright\ Rob Schluntz 2017 \\
+        \end{center}
+\end{titlepage}
+
+% The rest of the front pages should contain no headers and be numbered using Roman numerals starting with `ii'
+\pagestyle{plain}
+\setcounter{page}{2}
+
+\cleardoublepage % Ends the current page and causes all figures and tables that have so far appeared in the input to be printed.
+% In a two-sided printing style, it also makes the next page a right-hand (odd-numbered) page, producing a blank page if necessary.
+
+
+
+% D E C L A R A T I O N   P A G E
+% -------------------------------
+  % The following is the sample Delaration Page as provided by the GSO
+  % December 13th, 2006.  It is designed for an electronic thesis.
+  \noindent
+I hereby declare that I am the sole author of this thesis. This is a true copy of the thesis, including any required final revisions, as accepted by my examiners.
+
+  \bigskip
+
+  \noindent
+I understand that my thesis may be made electronically available to the public.
+
+\cleardoublepage
+%\newpage
+
+% A B S T R A C T
+% ---------------
+
+\begin{center}\textbf{Abstract}\end{center}
+
+% \CFA is a modern extension to the C programming language.
+% Some of the features of \CFA include parametric polymorphism, overloading, and .
+TODO
+
+\cleardoublepage
+%\newpage
+
+% A C K N O W L E D G E M E N T S
+% -------------------------------
+
+\begin{center}\textbf{Acknowledgements}\end{center}
+
+% I would like to thank all the little people who made this possible.
+TODO
+\cleardoublepage
+%\newpage
+
+% D E D I C A T I O N
+% -------------------
+
+\begin{center}\textbf{Dedication}\end{center}
+
+% This is dedicated to the one I love.
+TODO
+\cleardoublepage
+%\newpage
+
+% T A B L E   O F   C O N T E N T S
+% ---------------------------------
+\renewcommand\contentsname{Table of Contents}
+\tableofcontents
+\cleardoublepage
+\phantomsection
+%\newpage
+
+% L I S T   O F   T A B L E S
+% ---------------------------
+\addcontentsline{toc}{chapter}{List of Tables}
+\listoftables
+\cleardoublepage
+\phantomsection		% allows hyperref to link to the correct page
+%\newpage
+
+% L I S T   O F   F I G U R E S
+% -----------------------------
+\addcontentsline{toc}{chapter}{List of Figures}
+\listoffigures
+\cleardoublepage
+\phantomsection		% allows hyperref to link to the correct page
+%\newpage
+
+% L I S T   O F   S Y M B O L S
+% -----------------------------
+% To include a Nomenclature section
+% \addcontentsline{toc}{chapter}{\textbf{Nomenclature}}
+% \renewcommand{\nomname}{Nomenclature}
+% \printglossary
+% \cleardoublepage
+% \phantomsection % allows hyperref to link to the correct page
+% \newpage
+
+% Change page numbering back to Arabic numerals
+\pagenumbering{arabic}
+
Index: doc/rob_thesis/thesis.tex
===================================================================
--- doc/rob_thesis/thesis.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/thesis.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,292 @@
+% uWaterloo Thesis Template for LaTeX
+% Last Updated May 24, 2011 by Stephen Carr, IST Client Services
+% FOR ASSISTANCE, please send mail to rt-IST-CSmathsci@ist.uwaterloo.ca
+
+% Effective October 2006, the University of Waterloo
+% requires electronic thesis submission. See the uWaterloo thesis regulations at
+% http://www.grad.uwaterloo.ca/Thesis_Regs/thesistofc.asp.
+
+% DON'T FORGET TO ADD YOUR OWN NAME AND TITLE in the "hyperref" package
+% configuration below. THIS INFORMATION GETS EMBEDDED IN THE PDF FINAL PDF DOCUMENT.
+% You can view the information if you view Properties of the PDF document.
+
+% Many faculties/departments also require one or more printed
+% copies. This template attempts to satisfy both types of output.
+% It is based on the standard "book" document class which provides all necessary
+% sectioning structures and allows multi-part theses.
+
+% DISCLAIMER
+% To the best of our knowledge, this template satisfies the current uWaterloo requirements.
+% However, it is your responsibility to assure that you have met all
+% requirements of the University and your particular department.
+% Many thanks to the feedback from many graduates that assisted the development of this template.
+
+% -----------------------------------------------------------------------
+
+% By default, output is produced that is geared toward generating a PDF
+% version optimized for viewing on an electronic display, including
+% hyperlinks within the PDF.
+
+% E.g. to process a thesis called "mythesis.tex" based on this template, run:
+
+% pdflatex mythesis	-- first pass of the pdflatex processor
+% bibtex mythesis	-- generates bibliography from .bib data file(s)
+% pdflatex mythesis	-- fixes cross-references, bibliographic references, etc
+% pdflatex mythesis	-- fixes cross-references, bibliographic references, etc
+
+% If you use the recommended LaTeX editor, Texmaker, you would open the mythesis.tex
+% file, then click the pdflatex button. Then run BibTeX (under the Tools menu).
+% Then click the pdflatex button two more times. If you have an index as well,
+% you'll need to run MakeIndex from the Tools menu as well, before running pdflatex
+% the last two times.
+
+% N.B. The "pdftex" program allows graphics in the following formats to be
+% included with the "\includegraphics" command: PNG, PDF, JPEG, TIFF
+% Tip 1: Generate your figures and photos in the size you want them to appear
+% in your thesis, rather than scaling them with \includegraphics options.
+% Tip 2: Any drawings you do should be in scalable vector graphic formats:
+% SVG, PNG, WMF, EPS and then converted to PNG or PDF, so they are scalable in
+% the final PDF as well.
+% Tip 3: Photographs should be cropped and compressed so as not to be too large.
+
+% To create a PDF output that is optimized for double-sided printing:
+%
+% 1) comment-out the \documentclass statement in the preamble below, and
+% un-comment the second \documentclass line.
+%
+% 2) change the value assigned below to the boolean variable
+% "PrintVersion" from "false" to "true".
+
+% --------------------- Start of Document Preamble -----------------------
+
+% Specify the document class, default style attributes, and page dimensions
+% For hyperlinked PDF, suitable for viewing on a computer, use this:
+\PassOptionsToPackage{
+dvipsnames
+% ,monochrome % toggle black and white mode
+}{xcolor}
+\documentclass[letterpaper,12pt,titlepage,oneside,final]{book}
+
+\usepackage[T1]{fontenc}                                % allow Latin1 (extended ASCII) characters
+\usepackage{textcomp}
+% \usepackage[utf8]{inputenc}
+\usepackage[latin1]{inputenc}
+\usepackage{fullpage,times,comment}
+% \usepackage{epic,eepic}
+\usepackage{upquote}                                    % switch curled `'" to straight
+% \usepackage{calc}
+\usepackage{xspace}
+% \usepackage{graphicx}
+\usepackage{varioref}                                   % extended references
+\usepackage{listings}                                   % format program code
+% \usepackage[flushmargin]{footmisc}                      % support label/reference in footnote
+% \usepackage{latexsym}                                   % \Box glyph
+% \usepackage{mathptmx}                                   % better math font with "times"
+% \usepackage[usenames]{color}
+% \usepackage[pagewise]{lineno}
+% \renewcommand{\linenumberfont}{\scriptsize\sffamily}
+\usepackage{courier}
+\input{common}                                          % bespoke macros used in the document
+
+\usepackage{bigfoot}
+
+\interfootnotelinepenalty=10000
+
+% For PDF, suitable for double-sided printing, change the PrintVersion variable below
+% to "true" and use this \documentclass line instead of the one above:
+%\documentclass[letterpaper,12pt,titlepage,openright,twoside,final]{book}
+
+% Some LaTeX commands I define for my own nomenclature.
+% If you have to, it's better to change nomenclature once here than in a
+% million places throughout your thesis!
+\newcommand{\package}[1]{\textbf{#1}} % package names in bold text
+\newcommand{\cmmd}[1]{\textbackslash\texttt{#1}} % command name in tt font
+\newcommand{\href}[1]{#1} % does nothing, but defines the command so the
+    % print-optimized version will ignore \href tags (redefined by hyperref pkg).
+%\newcommand{\texorpdfstring}[2]{#1} % does nothing, but defines the command
+% Anything defined here may be redefined by packages added below...
+
+% This package allows if-then-else control structures.
+\usepackage{ifthen}
+\newboolean{PrintVersion}
+\setboolean{PrintVersion}{false}
+% CHANGE THIS VALUE TO "true" as necessary, to improve printed results for hard copies
+% by overriding some options of the hyperref package below.
+
+%\usepackage{nomencl} % For a nomenclature (optional; available from ctan.org)
+\usepackage{amsmath,amssymb,amstext} % Lots of math symbols and environments
+\usepackage[pdftex]{graphicx} % For including graphics N.B. pdftex graphics driver
+
+\input{cfa-format.tex}
+
+% Hyperlinks make it very easy to navigate an electronic document.
+% In addition, this is where you should specify the thesis title
+% and author as they appear in the properties of the PDF document.
+% Use the "hyperref" package
+% N.B. HYPERREF MUST BE THE LAST PACKAGE LOADED; ADD ADDITIONAL PKGS ABOVE
+\usepackage[pdftex,letterpaper=true,pagebackref=false]{hyperref} % with basic options
+		% N.B. pagebackref=true provides links back from the References to the body text. This can cause trouble for printing.
+\hypersetup{
+    plainpages=false,       % needed if Roman numbers in frontpages
+    pdfpagelabels=true,     % adds page number as label in Acrobat's page count
+    bookmarks=true,         % show bookmarks bar?
+    unicode=false,          % non-Latin characters in Acrobat’s bookmarks
+    pdftoolbar=true,        % show Acrobat’s toolbar?
+    pdfmenubar=true,        % show Acrobat’s menu?
+    pdffitwindow=false,     % window fit to page when opened
+    pdfstartview={FitH},    % fits the width of the page to the window
+    pdftitle={uWaterloo\ LaTeX\ Thesis\ Template},    % title: CHANGE THIS TEXT!
+    pdfauthor={Rob Schluntz},    % author: CHANGE THIS TEXT! and uncomment this line
+%    pdfsubject={Subject},  % subject: CHANGE THIS TEXT! and uncomment this line
+%    pdfkeywords={keyword1} {key2} {key3}, % list of keywords, and uncomment this line if desired
+    pdfnewwindow=true,      % links in new window
+    colorlinks=true,        % false: boxed links; true: colored links
+    linkcolor=blue,         % color of internal links
+    citecolor=green,        % color of links to bibliography
+    filecolor=magenta,      % color of file links
+    urlcolor=cyan           % color of external links
+}
+\ifthenelse{\boolean{PrintVersion}}{   % for improved print quality, change some hyperref options
+\hypersetup{	% override some previously defined hyperref options
+%    colorlinks,%
+    citecolor=black,%
+    filecolor=black,%
+    linkcolor=black,%
+    urlcolor=black}
+}{} % end of ifthenelse (no else)
+
+% Setting up the page margins...
+% uWaterloo thesis requirements specify a minimum of 1 inch (72pt) margin at the
+% top, bottom, and outside page edges and a 1.125 in. (81pt) gutter
+% margin (on binding side). While this is not an issue for electronic
+% viewing, a PDF may be printed, and so we have the same page layout for
+% both printed and electronic versions, we leave the gutter margin in.
+% Set margins to minimum permitted by uWaterloo thesis regulations:
+\setlength{\marginparwidth}{0pt} % width of margin notes
+% N.B. If margin notes are used, you must adjust \textwidth, \marginparwidth
+% and \marginparsep so that the space left between the margin notes and page
+% edge is less than 15 mm (0.6 in.)
+\setlength{\marginparsep}{0pt} % width of space between body text and margin notes
+\setlength{\evensidemargin}{0.125in} % Adds 1/8 in. to binding side of all
+% even-numbered pages when the "twoside" printing option is selected
+\setlength{\oddsidemargin}{0.125in} % Adds 1/8 in. to the left of all pages
+% when "oneside" printing is selected, and to the left of all odd-numbered
+% pages when "twoside" printing is selected
+\setlength{\textwidth}{6.375in} % assuming US letter paper (8.5 in. x 11 in.) and
+% side margins as above
+\raggedbottom
+
+% The following statement specifies the amount of space between
+% paragraphs. Other reasonable specifications are \bigskipamount and \smallskipamount.
+\setlength{\parskip}{\medskipamount}
+
+% The following statement controls the line spacing.  The default
+% spacing corresponds to good typographic conventions and only slight
+% changes (e.g., perhaps "1.2"), if any, should be made.
+\renewcommand{\baselinestretch}{1} % this is the default line space setting
+
+% By default, each chapter will start on a recto (right-hand side)
+% page.  We also force each section of the front pages to start on
+% a recto page by inserting \cleardoublepage commands.
+% In many cases, this will require that the verso page be
+% blank and, while it should be counted, a page number should not be
+% printed.  The following statements ensure a page number is not
+% printed on an otherwise blank verso page.
+\let\origdoublepage\cleardoublepage
+\newcommand{\clearemptydoublepage}{%
+  \clearpage{\pagestyle{empty}\origdoublepage}}
+\let\cleardoublepage\clearemptydoublepage
+
+%======================================================================
+%   L O G I C A L    D O C U M E N T -- the content of your thesis
+%======================================================================
+\begin{document}
+
+% For a large document, it is a good idea to divide your thesis
+% into several files, each one containing one chapter.
+% To illustrate this idea, the "front pages" (i.e., title page,
+% declaration, borrowers' page, abstract, acknowledgements,
+% dedication, table of contents, list of tables, list of figures,
+% nomenclature) are contained within the file "thesis-frontpgs.tex" which is
+% included into the document by the following statement.
+%----------------------------------------------------------------------
+% FRONT MATERIAL
+%----------------------------------------------------------------------
+\input{thesis-frontpgs}
+
+%----------------------------------------------------------------------
+% MAIN BODY
+%----------------------------------------------------------------------
+
+\input{intro}
+
+\input{ctordtor}
+
+\input{tuples}
+
+\input{conclusions}
+
+% The \appendix statement indicates the beginning of the appendices.
+% \appendix
+
+% % Add a title page before the appendices and a line in the Table of Contents
+% \chapter*{APPENDICES}
+% \addcontentsline{toc}{chapter}{APPENDICES}
+% %======================================================================
+% \chapter[PDF Plots From Matlab]{Matlab Code for Making a PDF Plot}
+% \label{AppendixA}
+% % Tip 4: Example of how to get a shorter chapter title for the Table of Contents
+% %======================================================================
+% \section{Using the GUI}
+% Properties of Matab plots can be adjusted from the plot window via a graphical interface. Under the Desktop menu in the Figure window, select the Property Editor. You may also want to check the Plot Browser and Figure Palette for more tools. To adjust properties of the axes, look under the Edit menu and select Axes Properties.
+
+% To set the figure size and to save as PDF or other file formats, click the Export Setup button in the figure Property Editor.
+
+% \section{From the Command Line}
+% All figure properties can also be manipulated from the command line. Here's an example:
+% \begin{verbatim}
+% x=[0:0.1:pi];
+% hold on % Plot multiple traces on one figure
+% plot(x,sin(x))
+% plot(x,cos(x),'--r')
+% plot(x,tan(x),'.-g')
+% title('Some Trig Functions Over 0 to \pi') % Note LaTeX markup!
+% legend('{\it sin}(x)','{\it cos}(x)','{\it tan}(x)')
+% hold off
+% set(gca,'Ylim',[-3 3]) % Adjust Y limits of "current axes"
+% set(gcf,'Units','inches') % Set figure size units of "current figure"
+% set(gcf,'Position',[0,0,6,4]) % Set figure width (6 in.) and height (4 in.)
+% cd n:\thesis\plots % Select where to save
+% print -dpdf plot.pdf % Save as PDF
+% \end{verbatim}
+
+%----------------------------------------------------------------------
+% END MATERIAL
+%----------------------------------------------------------------------
+
+% B I B L I O G R A P H Y
+% -----------------------
+
+% The following statement selects the style to use for references.  It controls the sort order of the entries in the bibliography and also the formatting for the in-text labels.
+\bibliographystyle{plain}
+% This specifies the location of the file containing the bibliographic information.
+% It assumes you're using BibTeX (if not, why not?).
+\cleardoublepage % This is needed if the book class is used, to place the anchor in the correct page,
+                 % because the bibliography will start on its own page.
+                 % Use \clearpage instead if the document class uses the "oneside" argument
+\phantomsection  % With hyperref package, enables hyperlinking from the table of contents to bibliography
+% The following statement causes the title "References" to be used for the bibliography section:
+\renewcommand*{\bibname}{References}
+
+% Add the References to the Table of Contents
+\addcontentsline{toc}{chapter}{\textbf{References}}
+
+\bibliography{cfa}
+% Tip 5: You can create multiple .bib files to organize your references.
+% Just list them all in the \bibliogaphy command, separated by commas (no spaces).
+
+% The following statement causes the specified references to be added to the bibliography% even if they were not
+% cited in the text. The asterisk is a wildcard that causes all entries in the bibliographic database to be included (optional).
+% \nocite{*}
+
+\end{document}
Index: doc/rob_thesis/tuples.tex
===================================================================
--- doc/rob_thesis/tuples.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
+++ doc/rob_thesis/tuples.tex	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -0,0 +1,1300 @@
+%======================================================================
+\chapter{Tuples}
+%======================================================================
+
+\section{Introduction}
+% TODO: named return values are not currently implemented in CFA - tie in with named tuples? (future work)
+% TODO: no passing input parameters by assignment, instead will have reference types => this is not a very C-like model and greatly complicates syntax for likely little gain (and would cause confusion with already supported return-by-rerefence)
+% TODO: tuples are allowed in expressions, exact meaning is defined by operator overloading (e.g. can add tuples). An important caveat to note is that it is currently impossible to allow adding two triples but prevent adding a pair with a quadruple (single flattening/structuring conversions are implicit, only total number of components matters). May be able to solve this with more nuanced conversion rules (future work)
+% TODO: benefits (conclusion) by Till: reduced number of variables and statements; no specified order of execution for multiple assignment (more optimzation freedom); can store parameter lists in variable; MRV routines (natural code); more convenient assignment statements; simple and efficient access of record fields; named return values more legible and efficient in use of storage
+
+\section{Multiple-Return-Value Functions}
+\label{s:MRV_Functions}
+In standard C, functions can return at most one value.
+This restriction results in code which 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.
+For example, consider a function returning the most frequently occuring letter in a string, and its frequency.
+% TODO: consider simplifying the example!
+%   Two things I like about this example:
+%   * it uses different types to illustrate why an array is insufficient (this is not necessary, but is nice)
+%   * it's complicated enough to show the uninitialized pitfall that exists in the aliasing example.
+%   Still, it may be a touch too complicated. Is there a simpler example with these two properties?
+\begin{cfacode}
+struct mf_ret {
+  int freq;
+  char ch;
+};
+
+struct mf_ret most_frequent(const char * str) {
+  char freqs [26] = { 0 };
+  struct mf_ret ret = { 0, 'a' };
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret.freq) {  // update on new max
+        ret.freq = freqs[idx];
+        ret.ch = ch;
+      }
+    }
+  }
+  return ret;
+}
+
+const char * str = "hello world";
+struct mf_ret ret = most_frequent(str);
+printf("%s -- %d %c\n", str, ret.freq, ret.ch);
+\end{cfacode}
+Of note, 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.
+That is, adding another named type creates another association in the programmer's mind that needs to be kept track of when reading and writing code.
+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 the same example,
+\begin{cfacode}
+int most_frequent(const char * str, char * ret_ch) {
+  char freqs [26] = { 0 };
+  int ret_freq = 0;
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret_freq) {  // update on new max
+        ret_freq = freqs[idx];
+        *ret_ch = ch;   // assign to out parameter
+      }
+    }
+  }
+  return ret_freq;  // only one value returned directly
+}
+
+const char * str = "hello world";
+char ch;                            // pre-allocate return value
+int freq = most_frequent(str, &ch); // pass return value as parameter
+printf("%s -- %d %c\n", str, freq, ch);
+\end{cfacode}
+Notably, using this approach, the caller is directly responsible for allocating storage for the additional temporary return values.
+This 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.
+There is a subtle bug in the previous example, in that @ret_ch@ is never assigned for a string that does not contain any letters, which can lead to undefined behaviour.
+As with the previous approach, this technique can simulate multiple return values, but in practice it is verbose and error prone.
+
+In \CFA, functions can be declared to return multiple values with an extension to the function declaration syntax.
+Multiple return values are declared as a comma-separated list of types in square brackets in the same location that the return type appears in standard C function declarations.
+The ability to return multiple values from a function requires a new syntax for the return statement.
+For consistency, the return statement in \CFA accepts a common-separated list of expressions in square brackets.
+The expression resolution phase of the \CFA translator ensures that the correct form is used depending on the values being returned and the return type of the current function.
+A multiple-returning function with return type @T@ can return any expression that is implicitly convertible to @T@.
+Using the running example, the @most_frequent@ function can be written in using multiple return values as such,
+\begin{cfacode}
+[int, char] most_frequent(const char * str) {
+  char freqs [26] = { 0 };
+  int ret_freq = 0;
+  char ret_ch = 'a';
+  for (int i = 0; str[i] != '\0'; ++i) {
+    if (isalpha(str[i])) {        // only count letters
+      int ch = tolower(str[i]);   // convert to lower case
+      int idx = ch-'a';
+      if (++freqs[idx] > ret_freq) {  // update on new max
+        ret_freq = freqs[idx];
+        ret_ch = ch;
+      }
+    }
+  }
+  return [ret_freq, ret_ch];
+}
+\end{cfacode}
+This approach provides the benefits of compile-time checking for appropriate return statements as in aggregation, but without the required verbosity of declaring a new named type.
+
+The addition of multiple-return-value functions necessitates a syntax for accepting multiple values at the call-site.
+The simplest mechanism for retaining a return value in C is variable assignment.
+By assigning the return value into a variable, its value can be retrieved later at any point in the program.
+As such, \CFA allows assigning multiple values from a function into multiple variables, using a square-bracketed list of lvalue expressions on the left side.
+\begin{cfacode}
+const char * str = "hello world";
+int freq;
+char ch;
+[freq, ch] = most_frequent(str);  // assign into multiple variables
+printf("%s -- %d %c\n", str, freq, ch);
+\end{cfacode}
+It is also common to use a function's output as the input to another function.
+\CFA also allows this case, without any new syntax.
+When a function call is passed as an argument to another call, the expression resolver attempts to find the best match of actual arguments to formal parameters given all of the possible expression interpretations in the current scope \cite{Bilson03}.
+For example,
+\begin{cfacode}
+void process(int);       // (1)
+void process(char);      // (2)
+void process(int, char); // (3)
+void process(char, int); // (4)
+
+process(most_frequent("hello world"));  // selects (3)
+\end{cfacode}
+In this case, there is only one option for a function named @most_frequent@ that takes a string as input.
+This function returns two values, one @int@ and one @char@.
+There are four options for a function named @process@, but only two which accept two arguments, and of those the best match is (3), which is also an exact match.
+This expression first calls @most_frequent("hello world")@, which produces the values @3@ and @'l'@, which are fed directly to the first and second parameters of (3), respectively.
+
+\section{Tuple Expressions}
+Multiple-return-value functions provide \CFA with a new syntax for expressing a combination of expressions in the return statement and a combination of types in a function signature.
+These notions can be generalized to provide \CFA with \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 3 \emph{components}.
+Each component in a tuple expression can be any \CFA expression, including another tuple expression.
+% TODO: Tuple expressions can appear anywhere that any other expression can appear (...?)
+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}.
+% TODO: does this statement still apply, and if so to what extent?
+%   Tuples are a compile-time phenomenon and have little to no run-time presence.
+
+\subsection{Tuple Variables}
+The call-site of the @most_frequent@ routine has a notable blemish, in that it required the preallocation of return variables in a manner similar to the aliasing example, since it is impossible to declare multiple variables of different types in the same declaration in standard C.
+In \CFA, it is possible to overcome this restriction by declaring a \emph{tuple variable}.
+\begin{cfacode}[emph=ret, emphstyle=\color{red}]
+const char * str = "hello world";
+[int, char] ret = most_frequent(str);  // initialize tuple variable
+printf("%s -- %d %c\n", str, ret);
+\end{cfacode}
+It is now possible to accept multiple values into a single piece of storage, in much the same way that it was previously possible to pass multiple values from one function call to another.
+These variables can be used in any of the contexts where a tuple expression is allowed, such as in the @printf@ function call.
+As in the @process@ example, the components of the tuple value are passed as separate parameters to @printf@, allowing very simple printing of tuple expressions.
+If the individual components are required, they can be extracted with a simple assignment, as in previous examples.
+\begin{cfacode}
+int freq;
+char ch;
+[freq, ch] = ret;
+\end{cfacode}
+
+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 do not carry their size around, which makes tuple assignment difficult when a tuple contains an array.
+\begin{cfacode}
+[double, int] di;
+[double, int] * pdi
+[double, int] adi[10];
+\end{cfacode}
+This examples declares a variable of type @[double, int]@, a variable of type pointer to @[double, int]@, and an array of ten @[double, int]@.
+
+\subsection{Tuple Indexing}
+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{cfacode}
+[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{cfacode}
+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 \KWC but never implemented \cite[p.~45]{Till89}.
+
+\subsection{Flattening and Structuring}
+As evident in previous examples, tuples in \CFA do not have a rigid structure.
+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{cfacode}
+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{cfacode}
+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 \KWC \cite{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, i.e. it takes a tuple with tuple components and expands it into a tuple with only non-tuple components.
+Structuring moves in the opposite direction, i.e. 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{cfacode}
+int f(int, [double, int]);
+f([5, 10.2], 4);
+\end{cfacode}
+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])@.
+
+\section{Tuple Assignment}
+\label{s:TupleAssignment}
+An assignment where the left side of the assignment operator has a tuple type is called tuple assignment.
+There 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 Multiple and Mass Assignment, respectively.
+\begin{cfacode}
+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{cfacode}
+Let $L_i$ for $i$ in $[0, n)$ represent each component of the flattened left side, $R_i$ represent each component of the flattened right side of a multiple assignment, and $R$ represent the right 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@ happen.
+
+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 differs from C cascading assignment (e.g. @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{cfacode}
+int x = 10, y = 20;
+[x, y] = [y, x];
+\end{cfacode}
+After executing this code, @x@ has the value @20@ and @y@ has the value @10@.
+
+In \CFA, tuple assignment is an expression where the result type is the type of the left 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 \KWC \cite{Till89}, wherein tuple assignment was a statement that allows cascading assignments as a special case.
+This decision wa 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.
+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 that is not an expression.
+In addition, \KWC permits the compiler to optimize tuple assignment as a block copy, since it does not support user-defined assignment operators.
+This optimization could be implemented in \CFA, but it requires the compiler to verify that the selected assignment operator is trivial.
+
+The following example shows multiple, mass, and cascading assignment used in one expression
+\begin{cfacode}
+  int a, b;
+  double c, d;
+  [void] f([int, int]);
+  f([c, a] = [b, d] = 1.5);  // assignments in parameter list
+\end{cfacode}
+The tuple expression begins with a mass assignment of @1.5@ into @[b, d]@, which assigns @1.5@ into @b@, which is truncated to @1@, and @1.5@ into @d@, producing the tuple @[1, 1.5]@ as a result.
+That tuple is used as the right side of the multiple assignment (i.e., @[c, a] = [1, 1.5]@) that assigns @1@ into @c@ and @1.5@ into @a@, which is truncated to @1@, producing the result @[1, 1]@.
+Finally, the tuple @[1, 1]@ is used as an expression in the call to @f@.
+
+\subsection{Tuple Construction}
+Tuple construction and destruction follow the same rules and semantics as tuple assignment, except that in the case where there is no right side, the default constructor or destructor is called on each component of the tuple.
+\begin{cfacode}
+struct S;
+void ?{}(S *);         // (1)
+void ?{}(S *, int);    // (2)
+void ?{}(S * double);  // (3)
+void ?{}(S *, S);      // (4)
+
+[S, S] x = [3, 6.28];  // uses (2), (3)
+[S, S] y;              // uses (1), (1)
+[S, S] z = x.0;        // uses (4), (4)
+\end{cfacode}
+In this example, @x@ is initialized by the multiple constructor calls @?{}(&x.0, 3)@ and @?{}(&x.1, 6.28)@, while @y@ is initilaized by two default constructor calls @?{}(&y.0)@ and @?{}(&y.1)@.
+@z@ is initialized by mass copy constructor calls @?{}(&z.0, x.0)@ and @?{}(&z.1, x.0)@.
+Finally, @x@, @y@, and @z@ are destructed, i.e. the calls @^?{}(&x.0)@, @^?{}(&x.1)@, @^?{}(&y.0)@, @^?{}(&y.1)@, @^?{}(&z.0)@, and @^?{}(&z.1)@.
+
+It is possible to define constructors and assignment functions for tuple types that provide new semantics, if the existing semantics do not fit the needs of an application.
+For example, the function @void ?{}([T, U] *, S);@ can be defined to allow a tuple variable to be constructed from a value of type @S@.
+\begin{cfacode}
+struct S { int x; double y; };
+void ?{}([int, double] * this, S s) {
+  this->0 = s.x;
+  this->1 = s.y;
+}
+\end{cfacode}
+Due to the structure of generated constructors, it is possible to pass a tuple to a generated constructor for a type with a member prefix that matches the type of the tuple.
+For example,
+\begin{cfacode}
+struct S { int x; double y; int z };
+[int, double] t;
+S s = t;
+\end{cfacode}
+The initialization of @s@ with @t@ works by default, because @t@ is flattened into its components, which satisfies the generated field constructor @?{}(S *, int, double)@ to initialize the first two values.
+
+\section{Member-Access Tuple Expression}
+\label{s:MemberAccessTuple}
+It is possible to access multiple fields from a single expression using a \emph{Member-Access Tuple Expression}.
+The result is a single tuple-valued expression whose type is the tuple of the types of the members.
+For example,
+\begin{cfacode}
+struct S { int x; double y; char * z; } s;
+s.[x, y, z];
+\end{cfacode}
+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 (e.g. rearrange components, drop components, duplicate components, etc.).
+\begin{cfacode}
+[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{cfacode}
+
+It is possible for a member tuple expression to contain other member access expressions.
+For example,
+\begin{cfacode}
+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{cfacode}
+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.
+\begin{cfacode}
+[int, float, double] f();
+[double, float] x = f().[2, 1];
+\end{cfacode}
+
+In \KWC, member tuple expressions are known as \emph{record field tuples} \cite{Till89}.
+Since \CFA permits these tuple-access expressions using structures, unions, and tuples, \emph{member tuple expression} or \emph{field tuple expression} is more appropriate.
+
+It could be possible to extend member-access expressions further.
+Currently, a member-access expression whose member is a name requires that the aggregate is a structure or union, while a constant integer member requires the aggregate to be a tuple.
+In the interest of orthogonal design, \CFA could apply some meaning to the remaining combinations as well.
+For example,
+\begin{cfacode}
+struct S { int x, y; } s;
+[S, S] z;
+
+s.x;  // access member
+z.0;  // access component
+
+s.1;  // ???
+z.y;  // ???
+\end{cfacode}
+One possiblity is for @s.1@ to select the second member of @s@.
+Under this interpretation, it becomes possible to not only access members of a struct by name, but also by position.
+Likewise, it seems natural to open this mechanism to enumerations as well, wherein the left side would be a type, rather than an expression.
+One benefit of this interpretation is familiar, since it is extremely reminiscent of tuple-index expressions.
+On the other hand, it could be argued that this interpretation is brittle in that changing the order of members or adding new members to a structure becomes a brittle operation.
+This problem is less of a concern with tuples, since modifying a tuple affects only the code which directly uses that tuple, whereas modifying a structure has far reaching consequences with every instance of the structure.
+
+As for @z.y@, a natural interpretation would be to extend the meaning of member tuple expressions.
+That is, currently the tuple must occur as the member, i.e. to the right of the dot.
+Allowing tuples to the left of the dot could distribute the member across the elements of the tuple, in much the same way that member tuple expressions distribute the aggregate across the member tuple.
+In this example, @z.y@ expands to @[z.0.y, z.1.y]@, allowing what is effectively a very limited compile-time field-sections map operation, where the argument must be a tuple containing only aggregates having a member named @y@.
+It is questionable how useful this would actually be in practice, since generally structures are not designed to have names in common with other structures, and further this could cause maintainability issues in that it encourages programmers to adopt very simple naming conventions, to maximize the amount of overlap between different types.
+Perhaps more useful would be to allow arrays on the left side of the dot, which would likewise allow mapping a field access across the entire array, producing an array of the contained fields.
+The immediate problem with this idea is that C arrays do not carry around their size, which would make it impossible to use this extension for anything other than a simple stack allocated array.
+
+Supposing this feature works as described, it would be necessary to specify an ordering for the expansion of member access expressions versus member tuple expressions.
+\begin{cfacode}
+struct { int x, y; };
+[S, S] z;
+z.[x, y];  // ???
+// => [z.0, z.1].[x, y]
+// => [z.0.x, z.0.y, z.1.x, z.1.y]
+// or
+// => [z.x, z.y]
+// => [[z.0, z.1].x, [z.0, z.1].y]
+// => [z.0.x, z.1.x, z.0.y, z.1.y]
+\end{cfacode}
+Depending on exactly how the two tuples are combined, different results can be achieved.
+As such, a specific ordering would need to be imposed in order for this feature to be useful.
+Furthermore, this addition moves a member tuple expression's meaning from being clear statically to needing resolver support, since the member name needs to be distributed appropriately over each member of the tuple, which could itself be a tuple.
+
+Ultimately, both of these extensions introduce complexity into the model, with relatively little peceived benefit.
+
+\section{Casting}
+In C, the cast operator is used to explicitly convert between types.
+In \CFA, the cast operator has a secondary use, which is 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{cfacode}
+int f();     // (1)
+double f();  // (2)
+
+f();       // ambiguous - (1),(2) both equally viable
+(int)f();  // choose (2)
+\end{cfacode}
+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{cfacode}[numbers=left]
+int f();
+void g();
+
+(void)f();
+(int)g();
+
+struct A { int x; };
+(struct A)f();
+\end{cfacode}
+In C, line 4 is a valid cast, which calls @f@ and discards its result.
+On the other hand, line 5 is invalid, because @g@ does not produce a result, so requesting an @int@ to materialize from nothing is nonsensical.
+Finally, line 8 is also invalid, because in C casts only provide conversion between scalar types \cite{C11}.
+For consistency, this implies that any case wherein the number of components increases as a result of the cast is invalid, while casts which 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 discarding naturally follows the way that a cast to void works in C.
+
+For example,
+\begin{cfacode}
+  [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{cfacode}
+
+(1) discards the last element of the return value and converts the second element to type 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 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)]@).
+
+% will this always hold true? probably, as constructors should give all of the conversion power we need. if casts become function calls, what would they look like? would need a way to specify the target type, which seems awkward. Also, C++ basically only has this because classes are closed to extension, while we don't have that problem (can have floating constructors for any type).
+Note that a cast is not a function call in \CFA, so flattening and structuring conversions do not occur for cast expressions.
+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]@.
+
+\section{Polymorphism}
+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{cfacode}
+forall(otype T, dtype U)
+void f(T x, U * y);
+
+f([5, "hello"]);
+\end{cfacode}
+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 can contain otype and dtype components.
+For example, a plus operator can be written to add two triples of a type together.
+\begin{cfacode}
+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{cfacode}
+Note that due to the implicit tuple conversions, this function is not restricted to the addition of two triples.
+A call to this plus operator type checks as long as a total of 6 non-tuple arguments are passed after flattening, and all of the arguments have a common type which can bind to @T@, with a pairwise @?+?@ over @T@.
+For example, these expressions will also succeed and produce the same value.
+\begin{cfacode}
+([x.0, x.1]) + ([x.2, 10, 20, 30]);
+x.0 + ([x.1, x.2, 10, 20, 30]);
+\end{cfacode}
+This presents a potential problem if structure is important, as these three expressions look like they should have different meanings.
+Further, these calls can be made ambiguous by adding seemingly different functions.
+\begin{cfacode}
+forall(otype T | { T ?+?(T, T); })
+[T, T, T] ?+?([T, T] x, [T, T, T, T]);
+forall(otype T | { T ?+?(T, T); })
+[T, T, T] ?+?(T x, [T, T, T, T, T]);
+\end{cfacode}
+It is also important to note that these calls could be disambiguated if the function return types were different, as they likely would be for a reasonable implementation of @?+?@, since the return type is used in overload resolution.
+Still, this is a deficiency of the current argument matching algorithm, and depending on the function, differing return values may not always be appropriate.
+It's possible that this could be rectified by applying an appropriate cost to the structuring and flattening conversions, which are currently 0-cost conversions.
+Care would be needed in this case to ensure that exact matches do not incur such a cost.
+\begin{cfacode}
+void f([int, int], int, int);
+
+f([0, 0], 0, 0);    // no cost
+f(0, 0, 0, 0);      // cost for structuring
+f([0, 0,], [0, 0]); // cost for flattening
+f([0, 0, 0], 0);    // cost for flattening and structuring
+\end{cfacode}
+
+Until this point, it has been assumed that assertion arguments must match the parameter type exactly, modulo polymorphic specialization (i.e. no implicit conversions are applied to assertion arguments).
+This decision presents a conflict with the flexibility of tuples.
+\subsection{Assertion Inference}
+\begin{cfacode}
+int f([int, double], double);
+forall(otype T, otype U | { T f(T, U, U); })
+void g(T, U);
+g(5, 10.21);
+\end{cfacode}
+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 Bilson \cite{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{cfacode}
+int _thunk(int _p0, double _p1, double _p2) {
+  return f([_p0, _p1], _p2);
+}
+\end{cfacode}
+Essentially, this provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
+
+\section{Implementation}
+Tuples are implemented in the \CFA translator via a transformation into generic types.
+The first time an $N$-tuple is seen for each $N$ in a scope, a generic type with $N$ type parameters is generated.
+For example,
+\begin{cfacode}
+[int, int] f() {
+  [double, double] x;
+  [int, double, int] y;
+}
+\end{cfacode}
+Is transformed into
+\begin{cfacode}
+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{cfacode}
+
+Tuple expressions are then simply converted directly into compound literals
+\begin{cfacode}
+[5, 'x', 1.24];
+\end{cfacode}
+Becomes
+\begin{cfacode}
+(_tuple3_(int, char, double)){ 5, 'x', 1.24 };
+\end{cfacode}
+
+Since tuples are essentially structures, tuple indexing expressions are just field accesses.
+\begin{cfacode}
+void f(int, [double, char]);
+[int, double] x;
+
+x.0+x.1;
+printf("%d %g\n", x);
+f(x, 'z');
+\end{cfacode}
+Is transformed into
+\begin{cfacode}
+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{cfacode}
+Note that due to flattening, @x@ used in the argument position is converted into the list of its fields.
+In the call to @f@, a the second and third argument components are structured into a tuple argument.
+
+Expressions which 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{cfacode}
+void g(int, double);
+[int, double] h();
+g(h());
+\end{cfacode}
+Interally, this is converted to
+\begin{cfacode}
+void g(int, double);
+[int, double] h();
+let unq<0> = f() : g(unq<0>.0, unq<0>.1);  // notation?
+\end{cfacode}
+Ultimately, unique expressions are converted into two variables and an expression.
+\begin{cfacode}
+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{cfacode}
+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 true to true.
+Every subsequent evaluation of the unique expression then results in an access to the stored result of the actual expression.
+
+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, autogenerated, and builtin functions, and could analyze function bodies when they are available to recursively detect impurity, to eliminate some unique expressions.
+It's possible that unique expressions could be exposed to the user through a language feature, but it's not immediately obvious that there is a benefit to doing so.
+
+Tuple member expressions are recursively expanded into a list of member access expressions.
+\begin{cfacode}
+[int, [double, int, double], int]] x;
+x.[0, 1.[0, 2]];
+\end{cfacode}
+Which becomes
+\begin{cfacode}
+[x.0, [x.1.0, x.1.2]];
+\end{cfacode}
+Tuple member expressions also take advantage of unique expressions in the case of possible impurity.
+
+Finally, the various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions.
+For example, a mass assignment
+\begin{cfacode}
+int x, z;
+double y;
+[double, double] f();
+
+[x, y, z] = 1.5;            // mass assignment
+\end{cfacode}
+Generates the following
+\begin{cfacode}
+// [x, y, z] = 1.5;
+_tuple3_(int, double, int) _tmp_stmtexpr_ret0;
+({
+  // assign LHS address temporaries
+  int *__massassign_L0 = &x;    // ?{}
+  double *__massassign_L1 = &y; // ?{}
+  int *__massassign_L2 = &z;    // ?{}
+
+  // assign RHS value temporary
+  double __massassign_R0 = 1.5; // ?{}
+
+  ({ // tuple construction - construct statement expr return variable
+    // assign LHS address temporaries
+    int *__multassign_L0 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
+    double *__multassign_L1 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
+    int *__multassign_L2 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
+
+    // assign RHS value temporaries and perform mass assignment to L0, L1, L2
+    int __multassign_R0 = (*__massassign_L0=(int)__massassign_R0);   // ?{}
+    double __multassign_R1 = (*__massassign_L1=__massassign_R0);     // ?{}
+    int __multassign_R2 = (*__massassign_L2=(int)__massassign_R0);   // ?{}
+
+    // perform construction of statement expr return variable using
+    // RHS value temporary
+    ((*__multassign_L0 = __multassign_R0 /* ?{} */),
+     (*__multassign_L1 = __multassign_R1 /* ?{} */),
+     (*__multassign_L2 = __multassign_R2 /* ?{} */));
+  });
+  _tmp_stmtexpr_ret0;
+});
+({ // tuple destruction - destruct assign expr value
+  int *__massassign_L3 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
+  double *__massassign_L4 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
+  int *__massassign_L5 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
+  ((*__massassign_L3 /* ^?{} */),
+   (*__massassign_L4 /* ^?{} */),
+   (*__massassign_L5 /* ^?{} */));
+});
+\end{cfacode}
+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, e.g. in a unique expression.
+$N$ LHS variables are generated and constructed using the address of the tuple components, and a single RHS variable is generated to store the value of the RHS without any loss of precision.
+A nested statement expression is generated that performs the individual assignments and constructs the return value using the results of the individual assignments.
+Finally, the statement expression temporary is destroyed at the end of the expression.
+
+Similarly, a multiple assignment
+\begin{cfacode}
+[x, y, z] = [f(), 3];       // multiple assignment
+\end{cfacode}
+Generates
+\begin{cfacode}
+// [x, y, z] = [f(), 3];
+_tuple3_(int, double, int) _tmp_stmtexpr_ret0;
+({
+  // assign LHS address temporaries
+  int *__multassign_L0 = &x;    // ?{}
+  double *__multassign_L1 = &y; // ?{}
+  int *__multassign_L2 = &z;    // ?{}
+
+  // assign RHS value temporaries
+  _tuple2_(double, double) _tmp_cp_ret0;
+  _Bool _unq0_finished_ = 0;
+  double __multassign_R0 =
+    (_unq0_finished_ ?
+      _tmp_cp_ret0 :
+      (_tmp_cp_ret0=f(), _unq0_finished_=1, _tmp_cp_ret0)).0; // ?{}
+  double __multassign_R1 =
+    (_unq0_finished_ ?
+      _tmp_cp_ret0 :
+      (_tmp_cp_ret0=f(), _unq0_finished_=1, _tmp_cp_ret0)).1; // ?{}
+  ({ // tuple destruction - destruct f() return temporary - tuple destruction
+    // assign LHS address temporaries
+    double *__massassign_L3 = (double *)&_tmp_cp_ret0.0;  // ?{}
+    double *__massassign_L4 = (double *)&_tmp_cp_ret0.1;  // ?{}
+    // perform destructions - intrinsic, so NOP
+    ((*__massassign_L3 /* ^?{} */),
+     (*__massassign_L4 /* ^?{} */));
+  });
+  int __multassign_R2 = 3; // ?{}
+
+  ({ // tuple construction - construct statement expr return variable
+    // assign LHS address temporaries
+    int *__multassign_L3 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
+    double *__multassign_L4 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
+    int *__multassign_L5 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
+
+    // assign RHS value temporaries and perform multiple assignment to L0, L1, L2
+    int __multassign_R3 = (*__multassign_L0=(int)__multassign_R0);  // ?{}
+    double __multassign_R4 = (*__multassign_L1=__multassign_R1);    // ?{}
+    int __multassign_R5 = (*__multassign_L2=__multassign_R2);       // ?{}
+
+    // perform construction of statement expr return variable using
+    // RHS value temporaries
+    ((*__multassign_L3=__multassign_R3 /* ?{} */),
+     (*__multassign_L4=__multassign_R4 /* ?{} */),
+     (*__multassign_L5=__multassign_R5 /* ?{} */));
+  });
+  _tmp_stmtexpr_ret0;
+});
+({  // tuple destruction - destruct assign expr value
+  // assign LHS address temporaries
+  int *__massassign_L5 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
+  double *__massassign_L6 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
+  int *__massassign_L7 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
+  // perform destructions - intrinsic, so NOP
+  ((*__massassign_L5 /* ^?{} */),
+   (*__massassign_L6 /* ^?{} */),
+   (*__massassign_L7 /* ^?{} */));
+});
+\end{cfacode}
+The difference here is that $N$ RHS values are stored into separate temporary variables.
+
+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.
+There are other places where the \CFA translator makes use of GNU C extensions, such as its use of nested functions, so this is not a new restriction.
+
+\section{Variadic Functions}
+% TODO: should this maybe be its own chapter?
+C provides variadic functions through the manipulation of @va_list@ objects.
+A variadic function is one which 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.
+Two common argument descriptors are format strings or and counter parameters.
+It's 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's 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 function that is open to extension.
+For example, a simple function which sums $N$ @int@s,
+\begin{cfacode}
+int sum(int N, ...) {
+  va_list args;
+  va_start(args, N);
+  int ret = 0;
+  while(N) {
+    ret += va_arg(args, int);  // have to specify type
+    N--;
+  }
+  va_end(args);
+  return ret;
+}
+sum(3, 10, 20, 30);  // need to keep counter in sync
+\end{cfacode}
+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 \cite{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 generally 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 does not permit extensions to the format string syntax, so a programmer cannot extend the attribute to warn for mismatches with custom types.
+
+Needless to say, C's variadic functions are a deficient language feature.
+Two options were examined to provide better, type-safe variadic functions in \CFA.
+\subsection{Whole Tuple Matching}
+Option 1 is to change the argument matching algorithm, so that type parameters can match whole tuples, rather than just their components.
+This option could be implemented with two phases of argument matching when a function contains type parameters and the argument list contains tuple arguments.
+If flattening and structuring fail to produce a match, a second attempt at matching the function and argument combination is made where tuple arguments are not expanded and structure must match exactly, modulo non-tuple implicit conversions.
+For example:
+\begin{cfacode}
+  forall(otype T, otype U | { T g(U); })
+  void f(T, U);
+
+  [int, int] g([int, int, int, int]);
+
+  f([1, 2], [3, 4, 5, 6]);
+\end{cfacode}
+With flattening and structuring, the call is first transformed into @f(1, 2, 3, 4, 5, 6)@.
+Since the first argument of type @T@ does not have a tuple type, unification decides that @T=int@ and @1@ is matched as the first parameter.
+Likewise, @U@ does not have a tuple type, so @U=int@ and @2@ is accepted as the second parameter.
+There are now no remaining formal parameters, but there are remaining arguments and the function is not variadic, so the match fails.
+
+With the addition of an exact matching attempt, @T=[int,int]@ and @U=[int,int,int,int]@ and so the arguments type check.
+Likewise, when inferring assertion @g@, an exact match is found.
+
+This approach is strict with respect to argument structure by nature, which makes it syntactically awkward to use in ways that the existing tuple design is not.
+For example, consider a @new@ function which allocates memory using @malloc@ and constructs the result, using arbitrary arguments.
+\begin{cfacode}
+struct Array;
+void ?{}(Array *, int, int, int);
+
+forall(dtype T, otype Params | sized(T) | { void ?{}(T *, Params); })
+T * new(Params p) {
+  return malloc(){ p };
+}
+Array(int) * x = new([1, 2, 3]);
+\end{cfacode}
+The call to @new@ is not particularly appealing, since it requires the use of square brackets at the call-site, which is not required in any other function call.
+This shifts the burden from the compiler to the programmer, which is almost always wrong, and creates an odd inconsistency within the language.
+Similarly, in order to pass 0 variadic arguments, an explicit empty tuple must be passed into the argument list, otherwise the exact matching rule would not have an argument to bind against.
+
+It should be otherwise noted that the addition of an exact matching rule only affects the outcome for polymorphic type binding when tuples are involved.
+For non-tuple arguments, exact matching and flattening \& structuring are equivalent.
+For tuple arguments to a function without polymorphic formal parameters, flattening and structuring work whenever an exact match would have worked, since the tuple is flattened and implicitly restructured to its original structure.
+Thus there is nothing to be gained from permitting the exact matching rule to take effect when a function does not contain polymorphism and none of the arguments are tuples.
+
+Overall, this option takes a step in the right direction, but is contrary to the flexibility of the existing tuple design.
+
+\subsection{A New Typeclass}
+A second option is the addition of another kind of type parameter, @ttype@.
+Matching against a @ttype@ 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.
+% TODO: a similar rule exists in C/C++ for "..."
+This idea essentially matches normal variadic semantics, with a strong feeling of similarity to \CCeleven variadic templates.
+As such, @ttype@ variables will also be referred to as argument packs.
+This is the option that has been added to \CFA.
+
+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, a simple translation of the C sum function using @ttype@ would look like
+\begin{cfacode}
+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{cfacode}
+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 which matches @int sum(int, int)@ is required.
+Like in the previous iteration, (0) is not a valid candiate, 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 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))@.
+
+A point of note is that 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, which could be done simply
+\begin{cfacode}
+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);
+}
+sum(10, 20, 30);
+\end{cfacode}
+
+One more iteration permits the summation of any summable type, as long as all arguments are the same type.
+\begin{cfacode}
+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);
+}
+sum(3, 10, 20, 30);
+\end{cfacode}
+Unlike C, it is not necessary to hard code the expected type.
+This 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.
+
+Going one last step, it is possible to achieve full generality in \CFA, allowing the summation of arbitrary lists of summable types.
+\begin{cfacode}
+trait summable(otype T1, otype T2, otype R) {
+  R ?+?(T1, T2);
+};
+forall(otype T1, otype T2, otype R | summable(T1, T2, R))
+R sum(T1 x, T2 y) {
+  return x+y;
+}
+forall(otype T1, otype T2, otype T3, ttype Params, otype R
+  | summable(T1, T2, T3)
+  | { R sum(T3, Params); })
+R sum(T1 x, T2 y, Params rest ) {
+  return sum(x+y, rest);
+}
+sum(3, 10.5, 20, 30.3);
+\end{cfacode}
+The \CFA translator requires adding explicit @double ?+?(int, double)@ and @double ?+?(double, int)@ functions for this call to work, since implicit conversions are not supported for assertions.
+
+C variadic syntax and @ttype@ polymorphism probably should not be mixed, since it is not clear where to draw the line to decide which arguments belong where.
+Furthermore, it might be desirable to disallow polymorphic functions to use C variadic syntax to encourage a Cforall style.
+Aside from calling C variadic functions, it is not obvious that there is anything that can be done with C variadics that could not also be done with @ttype@ parameters.
+
+Variadic templates in \CC require an ellipsis token to express that a parameter is a parameter pack and to expand a parameter pack.
+\CFA does not need an ellipsis in either case, since the type class @ttype@ is only used for variadics.
+An alternative design could have used an ellipsis combined with an existing type class.
+This approach was not taken because the largest benefit of the ellipsis token in \CC is the ability to expand a parameter pack within an expression, e.g. in fold expressions, which requires compile-time knowledge of the structure of the parameter pack, which is not available in \CFA.
+\begin{cppcode}
+template<typename... Args>
+void f(Args &... args) {
+  g(&args...);  // expand to addresses of pack elements
+}
+\end{cppcode}
+As such, the addition of an ellipsis token would be purely an aesthetic change in \CFA today.
+
+It is possible to write a type-safe variadic print routine, which can replace @printf@
+\begin{cfacode}
+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{cfacode}
+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.
+Example 2: new (i.e. type-safe malloc + constructors)
+\begin{cfacode}
+struct Array;
+void ?{}(Array *, int, int, int);
+
+forall(dtype T, ttype Params | sized(T) | { void ?{}(T *, Params); })
+T * new(Params p) {
+  return malloc(){ p }; // construct result of malloc
+}
+Array * x = new(1, 2, 3);
+\end{cfacode}
+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 provides the type-safety of @new@ in \CC, without the need to specify the allocated type, thanks to return-type inference.
+
+In the call to @new@, @Array@ is selected to match @T@, and @Params@ is expanded to match @[int, int, int, int]@. To satisfy the assertions, a constructor with an interface compatible with @void ?{}(Array *, int, int, int)@ must exist in the current scope.
+
+\subsection{Implementation}
+
+The definition of @new@
+\begin{cfacode}
+forall(dtype T | sized(T)) T * malloc();
+
+forall(dtype T, ttype Params | sized(T) | { void ?{}(T *, Params); })
+T * new(Params p) {
+  return malloc(){ p }; // construct result of malloc
+}
+\end{cfacode}
+Generates the following
+\begin{cfacode}
+void *malloc(long unsigned int _sizeof_T, long unsigned int _alignof_T);
+
+void *new(
+  void (*_adapter_)(void (*)(), void *, void *),
+  long unsigned int _sizeof_T,
+  long unsigned int _alignof_T,
+  long unsigned int _sizeof_Params,
+  long unsigned int _alignof_Params,
+  void (* _ctor_T)(void *, void *),
+  void *p
+){
+  void *_retval_new;
+  void *_tmp_cp_ret0;
+  void *_tmp_ctor_expr0;
+  _retval_new=
+    (_adapter_(_ctor_T,
+      (_tmp_ctor_expr0=(_tmp_cp_ret0=malloc(_sizeof_2tT, _alignof_2tT),
+        _tmp_cp_ret0)),
+      p),
+    _tmp_ctor_expr0); // ?{}
+  *(void **)&_tmp_cp_ret0; // ^?{}
+  return _retval_new;
+}
+\end{cfacode}
+The constructor for @T@ is called indirectly through the adapter function on the result of @malloc@ and the parameter pack.
+The variable that was allocated and constructed is then returned from @new@.
+
+A call to @new@
+\begin{cfacode}
+struct S { int x, y; };
+void ?{}(S *, int, int);
+
+S * s = new(3, 4);
+\end{cfacode}
+Generates the following
+\begin{cfacode}
+struct _tuple2_ {  // _tuple2_(T0, T1)
+  void *field_0;
+  void *field_1;
+};
+struct _conc__tuple2_0 {  // _tuple2_(int, int)
+  int field_0;
+  int field_1;
+};
+struct _conc__tuple2_0 _tmp_cp1;  // tuple argument to new
+struct S *_tmp_cp_ret1;           // return value from new
+void _thunk0(  // ?{}(S *, [int, int])
+  struct S *_p0,
+  struct _conc__tuple2_0 _p1
+){
+  _ctor_S(_p0, _p1.field_0, _p1.field_1);  // restructure tuple parameter
+}
+void _adapter(void (*_adaptee)(), void *_p0, void *_p1){
+  // apply adaptee to arguments after casting to actual types
+  ((void (*)(struct S *, struct _conc__tuple2_0))_adaptee)(
+    _p0,
+    *(struct _conc__tuple2_0 *)_p1
+  );
+}
+struct S *s = (struct S *)(_tmp_cp_ret1=
+  new(
+    _adapter,
+    sizeof(struct S),
+    __alignof__(struct S),
+    sizeof(struct _conc__tuple2_0),
+    __alignof__(struct _conc__tuple2_0),
+    (void (*)(void *, void *))&_thunk0,
+    (({ // copy construct tuple argument to new
+      int *__multassign_L0 = (int *)&_tmp_cp1.field_0;
+      int *__multassign_L1 = (int *)&_tmp_cp1.field_1;
+      int __multassign_R0 = 3;
+      int __multassign_R1 = 4;
+      ((*__multassign_L0=__multassign_R0 /* ?{} */) ,
+       (*__multassign_L1=__multassign_R1 /* ?{} */));
+    }), &_tmp_cp1)
+  ), _tmp_cp_ret1);
+*(struct S **)&_tmp_cp_ret1; // ^?{}  // destroy return value from new
+({  // destroy argument temporary
+  int *__massassign_L0 = (int *)&_tmp_cp1.field_0;
+  int *__massassign_L1 = (int *)&_tmp_cp1.field_1;
+  ((*__massassign_L0 /* ^?{} */) , (*__massassign_L1 /* ^?{} */));
+});
+\end{cfacode}
+Of note, @_thunk0@ is generated to translate calls to @?{}(S *, [int, int])@ into calls to @?{}(S *, int, int)@.
+The call to @new@ constructs a tuple argument using the supplied arguments.
+
+The @print@ function
+\begin{cfacode}
+forall(otype T, ttype Params |
+  { void print(T); void print(Params); })
+void print(T arg, Params rest) {
+  print(arg);
+  print(rest);
+}
+\end{cfacode}
+Generates
+\begin{cfacode}
+void print_variadic(
+  void (*_adapterF_7tParams__P)(void (*)(), void *),
+  void (*_adapterF_2tT__P)(void (*)(), void *),
+  void (*_adapterF_P2tT2tT__MP)(void (*)(), void *, void *),
+  void (*_adapterF2tT_P2tT2tT_P_MP)(void (*)(), void *, void *, void *),
+  long unsigned int _sizeof_T,
+  long unsigned int _alignof_T,
+  long unsigned int _sizeof_Params,
+  long unsigned int _alignof_Params,
+  void *(*_assign_TT)(void *, void *),
+  void (*_ctor_T)(void *),
+  void (*_ctor_TT)(void *, void *),
+  void (*_dtor_T)(void *),
+  void (*print_T)(void *),
+  void (*print_Params)(void *),
+  void *arg,
+  void *rest
+){
+  void *_tmp_cp0 = __builtin_alloca(_sizeof_T);
+  _adapterF_2tT__P(  // print(arg)
+    ((void (*)())print_T),
+    (_adapterF_P2tT2tT__MP( // copy construct argument
+      ((void (*)())_ctor_TT),
+      _tmp_cp0,
+      arg
+    ), _tmp_cp0)
+  );
+  _dtor_T(_tmp_cp0);  // destroy argument temporary
+  _adapterF_7tParams__P(  // print(rest)
+    ((void (*)())print_Params),
+    rest
+  );
+}
+\end{cfacode}
+The @print_T@ routine is called indirectly through an adapter function with a copy constructed argument, followed by an indirect call to @print_Params@.
+
+A call to print
+\begin{cfacode}
+void print(const char * x) { printf("%s", x); }
+void print(int x) { printf("%d", x);  }
+
+print("x = ", 123, ".\n");
+\end{cfacode}
+Generates the following
+\begin{cfacode}
+void print_string(const char *x){
+  int _tmp_cp_ret0;
+  (_tmp_cp_ret0=printf("%s", x)) , _tmp_cp_ret0;
+  *(int *)&_tmp_cp_ret0; // ^?{}
+}
+void print_int(int x){
+  int _tmp_cp_ret1;
+  (_tmp_cp_ret1=printf("%d", x)) , _tmp_cp_ret1;
+  *(int *)&_tmp_cp_ret1; // ^?{}
+}
+
+struct _tuple2_ {  // _tuple2_(T0, T1)
+  void *field_0;
+  void *field_1;
+};
+struct _conc__tuple2_0 {  // _tuple2_(int, const char *)
+  int field_0;
+  const char *field_1;
+};
+struct _conc__tuple2_0 _tmp_cp6;  // _tuple2_(int, const char *)
+const char *_thunk0(const char **_p0, const char *_p1){
+        // const char * ?=?(const char **, const char *)
+  return *_p0=_p1;
+}
+void _thunk1(const char **_p0){ // void ?{}(const char **)
+  *_p0; // ?{}
+}
+void _thunk2(const char **_p0, const char *_p1){
+        // void ?{}(const char **, const char *)
+  *_p0=_p1; // ?{}
+}
+void _thunk3(const char **_p0){ // void ^?{}(const char **)
+  *_p0; // ^?{}
+}
+void _thunk4(struct _conc__tuple2_0 _p0){ // void print([int, const char *])
+  struct _tuple1_ { // _tuple1_(T0)
+    void *field_0;
+  };
+  struct _conc__tuple1_1 { // _tuple1_(const char *)
+    const char *field_0;
+  };
+  void _thunk5(struct _conc__tuple1_1 _pp0){ // void print([const char *])
+    print_string(_pp0.field_0);  // print(rest.0)
+  }
+  void _adapter_i_pii_(void (*_adaptee)(), void *_ret, void *_p0, void *_p1){
+    *(int *)_ret=((int (*)(int *, int))_adaptee)(_p0, *(int *)_p1);
+  }
+  void _adapter_pii_(void (*_adaptee)(), void *_p0, void *_p1){
+    ((void (*)(int *, int ))_adaptee)(_p0, *(int *)_p1);
+  }
+  void _adapter_i_(void (*_adaptee)(), void *_p0){
+    ((void (*)(int))_adaptee)(*(int *)_p0);
+  }
+  void _adapter_tuple1_5_(void (*_adaptee)(), void *_p0){
+    ((void (*)(struct _conc__tuple1_1 ))_adaptee)(*(struct _conc__tuple1_1 *)_p0);
+  }
+  print_variadic(
+    _adapter_tuple1_5,
+    _adapter_i_,
+    _adapter_pii_,
+    _adapter_i_pii_,
+    sizeof(int),
+    __alignof__(int),
+    sizeof(struct _conc__tuple1_1),
+    __alignof__(struct _conc__tuple1_1),
+    (void *(*)(void *, void *))_assign_i,     // int ?=?(int *, int)
+    (void (*)(void *))_ctor_i,                // void ?{}(int *)
+    (void (*)(void *, void *))_ctor_ii,       // void ?{}(int *, int)
+    (void (*)(void *))_dtor_ii,               // void ^?{}(int *)
+    (void (*)(void *))print_int,              // void print(int)
+    (void (*)(void *))&_thunk5,               // void print([const char *])
+    &_p0.field_0,                             // rest.0
+    &(struct _conc__tuple1_1 ){ _p0.field_1 } // [rest.1]
+  );
+}
+struct _tuple1_ {  // _tuple1_(T0)
+  void *field_0;
+};
+struct _conc__tuple1_6 {  // _tuple_1(const char *)
+  const char *field_0;
+};
+const char *_temp0;
+_temp0="x = ";
+void _adapter_pstring_pstring_string(
+  void (*_adaptee)(),
+  void *_ret,
+  void *_p0,
+  void *_p1
+){
+  *(const char **)_ret=
+    ((const char *(*)(const char **, const char *))_adaptee)(
+      _p0,
+      *(const char **)_p1
+    );
+}
+void _adapter_pstring_string(void (*_adaptee)(), void *_p0, void *_p1){
+  ((void (*)(const char **, const char *))_adaptee)(_p0, *(const char **)_p1);
+}
+void _adapter_string_(void (*_adaptee)(), void *_p0){
+  ((void (*)(const char *))_adaptee)(*(const char **)_p0);
+}
+void _adapter_tuple2_0_(void (*_adaptee)(), void *_p0){
+  ((void (*)(struct _conc__tuple2_0 ))_adaptee)(*(struct _conc__tuple2_0 *)_p0);
+}
+print_variadic(
+  _adapter_tuple2_0_,
+  _adapter_string_,
+  _adapter_pstring_string_,
+  _adapter_pstring_pstring_string_,
+  sizeof(const char *),
+  __alignof__(const char *),
+  sizeof(struct _conc__tuple2_0 ),
+  __alignof__(struct _conc__tuple2_0 ),
+  (void *(*)(void *, void *))&_thunk0, // const char * ?=?(const char **, const char *)
+  (void (*)(void *))&_thunk1,          // void ?{}(const char **)
+  (void (*)(void *, void *))&_thunk2,  // void ?{}(const char **, const char *)
+  (void (*)(void *))&_thunk3,          // void ^?{}(const char **)
+  (void (*)(void *))print_string,      // void print(const char *)
+  (void (*)(void *))&_thunk4,          // void print([int, const char *])
+  &_temp0,                             // "x = "
+  (({  // copy construct tuple argument to print
+    int *__multassign_L0 = (int *)&_tmp_cp6.field_0;
+    const char **__multassign_L1 = (const char **)&_tmp_cp6.field_1;
+    int __multassign_R0 = 123;
+    const char *__multassign_R1 = ".\n";
+    ((*__multassign_L0=__multassign_R0 /* ?{} */),
+     (*__multassign_L1=__multassign_R1 /* ?{} */));
+  }), &_tmp_cp6)                        // [123, ".\n"]
+);
+({  // destroy argument temporary
+  int *__massassign_L0 = (int *)&_tmp_cp6.field_0;
+  const char **__massassign_L1 = (const char **)&_tmp_cp6.field_1;
+  ((*__massassign_L0 /* ^?{} */) , (*__massassign_L1 /* ^?{} */));
+});
+\end{cfacode}
+The type @_tuple2_@ is generated to allow passing the @rest@ argument to @print_variadic@.
+Thunks 0 through 3 provide wrappers for the @otype@ parameters for @const char *@, while @_thunk4@ translates a call to @print([int, const char *])@ into a call to @print_variadic(int, [const char *])@.
+This all builds to a call to @print_variadic@, with the appropriate copy construction of the tuple argument.
Index: src/GenPoly/Box.cc
===================================================================
--- src/GenPoly/Box.cc	(revision d9c8a597c64732b01c6014a27959e095f47857ef)
+++ src/GenPoly/Box.cc	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -1298,5 +1298,5 @@
 			FunctionType * ftype = functionDecl->get_functionType();
 			if ( ! ftype->get_returnVals().empty() && functionDecl->get_statements() ) {
-				if ( functionDecl->get_name() != "?=?" && ! isPrefix( functionDecl->get_name(), "_thunk" ) ) { // xxx - remove check for ?=? once reference types are in; remove check for prefix once thunks properly use ctor/dtors
+				if ( functionDecl->get_name() != "?=?" && ! isPrefix( functionDecl->get_name(), "_thunk" ) && ! isPrefix( functionDecl->get_name(), "_adapter" ) ) { // xxx - remove check for ?=? once reference types are in; remove check for prefix once thunks properly use ctor/dtors
 					assert( ftype->get_returnVals().size() == 1 );
 					DeclarationWithType * retval = ftype->get_returnVals().front();
Index: src/GenPoly/Specialize.cc
===================================================================
--- src/GenPoly/Specialize.cc	(revision d9c8a597c64732b01c6014a27959e095f47857ef)
+++ src/GenPoly/Specialize.cc	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -168,4 +168,26 @@
 	}
 
+	struct EnvTrimmer : public Visitor {
+		TypeSubstitution * env, * newEnv;
+		EnvTrimmer( TypeSubstitution * env, TypeSubstitution * newEnv ) : env( env ), newEnv( newEnv ){}
+		virtual void visit( TypeDecl * tyDecl ) {
+			// transfer known bindings for seen type variables
+			if ( Type * t = env->lookup( tyDecl->get_name() ) ) {
+				newEnv->add( tyDecl->get_name(), t );
+			}
+		}
+	};
+
+	/// reduce environment to just the parts that are referenced in a given expression
+	TypeSubstitution * trimEnv( ApplicationExpr * expr, TypeSubstitution * env ) {
+		if ( env ) {
+			TypeSubstitution * newEnv = new TypeSubstitution();
+			EnvTrimmer trimmer( env, newEnv );
+			expr->accept( trimmer );
+			return newEnv;
+		}
+		return nullptr;
+	}
+
 	/// Generates a thunk that calls `actual` with type `funType` and returns its address
 	Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) {
@@ -211,5 +233,5 @@
 		}
 
-		appExpr->set_env( maybeClone( env ) );
+		appExpr->set_env( trimEnv( appExpr, env ) );
 		if ( inferParams ) {
 			appExpr->get_inferParams() = *inferParams;
Index: src/InitTweak/FixInit.cc
===================================================================
--- src/InitTweak/FixInit.cc	(revision d9c8a597c64732b01c6014a27959e095f47857ef)
+++ src/InitTweak/FixInit.cc	(revision ccd8bc3308d01e55eb13b2accbb24379e45243ab)
@@ -52,4 +52,5 @@
 	namespace {
 		typedef std::unordered_map< Expression *, TypeSubstitution * > EnvMap;
+		typedef std::unordered_map< int, int > UnqCount;
 
 		class InsertImplicitCalls final : public GenPoly::PolyMutator {
@@ -74,10 +75,10 @@
 			/// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
 			/// arguments and return value temporaries
-			static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap );
+			static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount );
 
 			typedef SymTab::Indexer Parent;
 			using Parent::visit;
 
-			ResolveCopyCtors( const EnvMap & envMap ) : envMap( envMap ) {}
+			ResolveCopyCtors( const EnvMap & envMap, UnqCount & unqCount ) : envMap( envMap ), unqCount( unqCount ) {}
 
 			virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
@@ -94,4 +95,5 @@
 			TypeSubstitution * env;
 			const EnvMap & envMap;
+			UnqCount & unqCount; // count the number of times each unique expr ID appears
 		};
 
@@ -202,7 +204,8 @@
 		class FixCopyCtors final : public GenPoly::PolyMutator {
 		  public:
+			FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
 			/// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
 			/// and destructors
-			static void fixCopyCtors( std::list< Declaration * > &translationUnit );
+			static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
 
 			typedef GenPoly::PolyMutator Parent;
@@ -211,4 +214,6 @@
 			virtual Expression * mutate( UniqueExpr * unqExpr ) override;
 			virtual Expression * mutate( StmtExpr * stmtExpr ) override;
+
+			UnqCount & unqCount;
 		};
 
@@ -272,12 +277,13 @@
 
 		EnvMap envMap;
+		UnqCount unqCount;
 
 		InsertImplicitCalls::insert( translationUnit, envMap );
-		ResolveCopyCtors::resolveImplicitCalls( translationUnit, envMap );
+		ResolveCopyCtors::resolveImplicitCalls( translationUnit, envMap, unqCount );
 		InsertDtors::insert( translationUnit );
 		FixInit::fixInitializers( translationUnit );
 
 		// FixCopyCtors must happen after FixInit, so that destructors are placed correctly
-		FixCopyCtors::fixCopyCtors( translationUnit );
+		FixCopyCtors::fixCopyCtors( translationUnit, unqCount );
 
 		GenStructMemberCalls::generate( translationUnit );
@@ -298,6 +304,6 @@
 		}
 
-		void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap ) {
-			ResolveCopyCtors resolver( envMap );
+		void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount ) {
+			ResolveCopyCtors resolver( envMap, unqCount );
 			acceptAll( translationUnit, resolver );
 		}
@@ -329,6 +335,6 @@
 		}
 
-		void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
-			FixCopyCtors fixer;
+		void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
+			FixCopyCtors fixer( unqCount );
 			mutateAll( translationUnit, fixer );
 		}
@@ -520,4 +526,5 @@
 		void ResolveCopyCtors::visit( UniqueExpr * unqExpr ) {
 			static std::unordered_set< int > vars;
+			unqCount[ unqExpr->get_id() ]++;  // count the number of unique expressions for each ID
 			if ( vars.count( unqExpr->get_id() ) ) {
 				// xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
@@ -636,4 +643,6 @@
 
 		Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
+			unqCount[ unqExpr->get_id() ]--;
+			static std::unordered_map< int, std::list< Statement * > > dtors;
 			static std::unordered_map< int, UniqueExpr * > unqMap;
 			static std::unordered_set< int > addDeref;
@@ -645,4 +654,7 @@
 				delete unqExpr->get_result();
 				unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
+				if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
+					stmtsToAdd.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
+				}
 				if ( addDeref.count( unqExpr->get_id() ) ) {
 					// other UniqueExpr was dereferenced because it was an lvalue return, so this one should be too
@@ -651,5 +663,7 @@
 				return unqExpr;
 			}
-			unqExpr = safe_dynamic_cast< UniqueExpr * >( Parent::mutate( unqExpr ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
+			FixCopyCtors fixer( unqCount );
+			unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
+			stmtsToAdd.splice( stmtsToAdd.end(), fixer.stmtsToAdd );
 			unqMap[unqExpr->get_id()] = unqExpr;
 			if ( UntypedExpr * deref = dynamic_cast< UntypedExpr * >( unqExpr->get_expr() ) ) {
@@ -661,4 +675,9 @@
 				getCallArg( deref, 0 ) = unqExpr;
 				addDeref.insert( unqExpr->get_id() );
+				if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
+					stmtsToAdd.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
+				} else { // remember dtors for last instance of unique expr
+					dtors[ unqExpr->get_id() ] = fixer.stmtsToAddAfter;
+				}
 				return deref;
 			}
