%======================================================================
\chapter{Constructors and Destructors}
%======================================================================

% 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]

% 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

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.

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.

Declaration initialization is insufficient, because it permits uninitialized variables to exist and because it does not allow for the insertion of arbitrary code before a variable is live.
Many C compilers give good warnings for uninitialized variables most of the time, but they cannot in all cases.
\begin{cfacode}
int f(int *);  // output parameter: never reads, only writes
int g(int *);  // input parameter: never writes, only reads,
               // so requires initialized variable

int x, y;
f(&x);  // okay - only writes to x
g(&y);  // uses 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 is not 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) { calloc(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 @?{}@.
Like other operators in \CFA, the name represents the syntax used to call the constructor, e.g., @struct S = { ... };@.
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, since there are no implicit checks for invalid values or reasonable defaults.
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}
The destructor is automatically called at deallocation for all objects of type @Array@.
Hence, 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 2, @z@ is initialized with the value of @x@, while on line 3, @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.
The four functions (default constructor, destructor, copy constructor, and assignment operator) are special in that they safely 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{Calling Syntax}
\label{sub:syntax}
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, second construction
?{}(y, x);  // explit construct y from x, second construction
^?{}(&x);   // explicit destroy x, in different order
^?{}(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 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.
This syntactic form is similar to the new initialization syntax in \CCeleven, except that it is used in expression contexts, rather than declaration contexts.
\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.

One of these three syntactic forms should appeal to either C or \CC programmers using \CFA.

\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 continues 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.
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 are 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 is still possible to add an @int@ to an enumeration, but the resulting value is an @int@, meaning it cannot be reassigned to an enumeration without a cast.

For structures, the situation is more complicated.
Given 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 copy constructs them, and so on.
For example, given the structure 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 prevent 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 structure'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 structures in \CFA to be used naturally in the same ways as used in C (i.e., to initialize any prefix of the structure), 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, unions may have managed members, with the caveat that 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.
This applies only to implicitly generated constructor calls.
Hence, explicitly re-initializing qualified objects with a constructor requires an explicit cast.

As discussed in Section \ref{sub:c_background}, compound literals create unnamed objects.
This mechanism can continue to be used seamlessly in \CFA with managed types to create temporary objects.
The object created by a compound literal is constructed using the provided brace-enclosed initializer-list, and is destructed at the end of the scope it is used in.
For example,
\begin{cfacode}
struct A { int x; };
void ?{}(A *, int, int);
{
  int x = (A){ 10, 20 }.x;
}
\end{cfacode}
is equivalent to
\begin{cfacode}
struct A { int x, y; };
void ?{}(A *, int, int);
{
  A _tmp;
  ?{}(&_tmp, 10, 20);
  int x = _tmp.x;
  ^?{}(&tmp);
}
\end{cfacode}

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 start/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, because of the explicit initializer.

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 a user declares any constructor or destructor, the corresponding intrinsic/generated function and all field constructors for that type are hidden, so that they are not found during expression resolution until the user-defined function goes out of scope.
Furthermore, if the user declares any constructor, then the intrinsic/generated default constructor is also hidden, precluding default construction.
These semantics closely mirror the rule for implicit declaration of constructors in \CC, wherein the default constructor is implicitly declared if there is no user-declared constructor \cite[p.~186]{ANSI98:C++}.
\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; } // locally hide autogen constructors
    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: 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). This might be okay in some situations, but it deserves a warning at the very least.
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.
\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}
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.
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.

In addition, constructor calls do not support unnamed nesting.
\begin{cfacode}
struct B { int x; };
struct C { int y; };
struct A { B b; C c; };
void ?{}(A *, B);
void ?{}(A *, C);

A a = {
  { 10 },  // construct B? - invalid
};
\end{cfacode}
In C, nesting initializers means that the programmer intends to initialize subobjects with the nested initializers.
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 *, B)@ or with @?{}(A *, C)@, since the inner initializer @{ 10 }@ could be taken as an intermediate object of type @B@ or @C@.
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.

More precisely, 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.

It should be noted that unmanaged objects can still make use of designations and nested initializers in \CFA.
It is simple to overcome this limitation for managed objects by making use of compound literals, so that the arguments to the constructor call are explicitly typed.

\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}

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 attempts 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;
  for (int j = 0; j < 10; j++) {
    A y;
    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@.
% TODO: "why not do this all the time? fix or justify"
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.
That is, since the parameter is not marked as an unmanaged object using \ateq, it will be copy constructed if it is returned by value or passed as an argument to another function, so to guarantee consistent behaviour, unmanaged objects must be copy constructed when passed as arguments.
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 identity(A x) { // pass by value => need local copy
  return x;       // return by value => make call-site copy
}

A y, z @= {};
identity(y);  // copy construct y into x
identity(z);  // copy construct z into x
\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.

This generates the following
\begin{cfacode}
struct A f(struct A x){
  struct A _retval_f;    // return value
  ?{}((&_retval_f), x);  // copy construct return value
  return _retval_f;
}

struct A y;
?{}(&y);                 // default construct
struct A z = { 0 };      // C default

struct A _tmp_cp1;       // argument 1
struct A _tmp_cp_ret0;   // return value
_tmp_cp_ret0=f(
  (?{}(&_tmp_cp1, y) , _tmp_cp1)  // argument is a comma expression
), _tmp_cp_ret0;         // return value for cascading
^?{}(&_tmp_cp_ret0);     // destruct return value
^?{}(&_tmp_cp1);         // destruct argument 1

struct A _tmp_cp2;       // argument 1
struct A _tmp_cp_ret1;   // return value
_tmp_cp_ret1=f(
  (?{}(&_tmp_cp2, z), _tmp_cp2)  // argument is a common expression
), _tmp_cp_ret1;         // return value for cascading
^?{}(&_tmp_cp_ret1);     // destruct return value
^?{}(&_tmp_cp2);         // destruct argument 1
^?{}(&y);
\end{cfacode}

A special syntactic form, such as a variant of \ateq, can be implemented to specify at the call site that an argument should not be copy constructed, to regain some control for the C programmer.
\begin{cfacode}
identity(z@);  // do not copy construct argument
               // - will copy construct/destruct return value
A@ identity_nocopy(A @ x) {  // argument not copy constructed or destructed
  return x;  // not copy constructed
             // return type marked @ => not destructed
}
\end{cfacode}
It should be noted that reference types will allow specifying that a value does not need to be copied, however reference types do not provide a means of preventing implicit copy construction from uses of the reference, so the problem is still present when passing or returning the reference by value.

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 that use the @this@ pointer as a unique identifier to store data externally do not work correctly for return value objects.
Thus, it is 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
      // ...
    }
  }
}

A makeA() {
  A x;  // stores &x in external_data
  return x;
}
makeA();  // return temporary has a different address than x
// equivalent to:
//   A _tmp;
//   _tmp = makeA(), _tmp;
//   ^?{}(&_tmp);
\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 does 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 changing 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 that 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, since only trivial constructors are available
{
  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 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 is not 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 that 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.
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. % TODO: 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}

%   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
GCC provides an attribute @init_priority@, which specifies allows specifying the relative priority for initialization of global objects on a per-object basis in \CC.
A similar attribute can be implemented in \CFA by pulling marked objects into global constructor/destructor-attribute functions with the specified priority.
For example,
\begin{cfacode}
struct A { ... };
void ?{}(A *, int);
void ^?{}(A *);
__attribute__((init_priority(200))) A x = { 123 };
\end{cfacode}
would generate
\begin{cfacode}
A x;
__attribute__((constructor(200))) __init_x() {
  ?{}(&x, 123);  // construct x with priority 200
}
__attribute__((destructor(200))) __destroy_x() {
  ?{}(&x);       // destruct x with priority 200
}
\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 can only be initialized to a \emph{compile-time constant value} so that a compiler is able to create storage for the variable and initialize it at compile-time.

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 do 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}

% TODO: move this section forward?? maybe just after constructor syntax? would need to remove _tmp_cp_ret0, since copy constructors are not discussed yet, but this might not be a big issue.
\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.
A key example for this capability 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@.
