Ignore:
Timestamp:
Apr 19, 2017, 10:15:45 AM (5 years ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
aaron-thesis, arm-eh, cleanup-dtors, deferred_resn, demangler, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, resolv-new, with_gc
Children:
cd348e7
Parents:
221c2de (diff), de4ce0e (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/rob_thesis/ctordtor.tex

    r221c2de r154fdc8  
    33%======================================================================
    44
    5 % TODO: discuss move semantics; they haven't been implemented, but could be. Currently looking at alternative models. (future work)
    6 
    7 % TODO: as an experiment, implement Andrei Alexandrescu's ScopeGuard http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758?pgno=2
     5% TODO now: as an experiment, implement Andrei Alexandrescu's ScopeGuard http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758?pgno=2
    86% doesn't seem possible to do this without allowing ttype on generic structs?
    97
    10 % If a Cforall constructor is in scope, C style initialization is
    11 % disabled by default.
    12 % * initialization rule: if any constructor is in scope for type T, try
    13 %   to find a matching constructor for the call. If there are no
    14 %   constructors in scope for type T, then attempt to fall back on
    15 %   C-style initialization.
    16 % + if this rule was not in place, it would be easy to accidentally
    17 %   use C-style initialization in certain cases, which could lead to
    18 %   subtle errors [2]
    19 % - this means we need special syntax if we want to allow users to force
    20 %   a C-style initialization (to give users more control)
    21 % - two different declarations in the same scope can be implicitly
    22 %   initialized differently. That is, there may be two objects of type
    23 %   T that are initialized differently because there is a constructor
    24 %   definition between them. This is not technically specific to
    25 %   constructors.
    26 
    27 % C-style initializers can be accessed with @= syntax
    28 % + provides a way to get around the requirement of using a constructor
    29 %   (for advanced programmers only)
    30 % - can break invariants in the type => unsafe
    31 % * provides a way of asserting that a variable is an instance of a
    32 %   C struct (i.e. a POD struct), and so will not be implicitly
    33 %   destructed (this can be useful at times, maybe mitigates the need
    34 %   for move semantics?) [3]
    35 % + can modernize a code base one step at a time
    36 
    37 % Cforall constructors can be used in expressions to initialize any
    38 % piece of memory.
    39 % + malloc() { ... } calls the appropriate constructor on the newly
    40 %   allocated space; the argument is moved into the constructor call
    41 %   without taking its address [4]
    42 % - with the above form, there is still no way to ensure that
    43 %   dynamically allocated objects are constructed. To resolve this,
    44 %   we might want a stronger "new" function which always calls the
    45 %   constructor, although how we accomplish that is currently still
    46 %   unresolved (compiler magic vs. better variadic functions?)
    47 % + This can be used as a placement syntax [5]
    48 % - can call the constructor on an object more than once, which could
    49 %   cause resource leaks and reinitialize const fields (can try to
    50 %   detect and prevent this in some cases)
    51 %   * compiler always tries to implicitly insert a ctor/dtor pair for
    52 %     non-@= objects.
    53 %     * For POD objects, this will resolve to an autogenerated or
    54 %       intrinsic function.
    55 %     * Intrinsic functions are not automatically called. Autogenerated
    56 %       are, because they may call a non-autogenerated function.
    57 %     * destructors are automatically inserted at appropriate branches
    58 %       (e.g. return, break, continue, goto) and at the end of the block
    59 %       in which they are declared.
    60 %   * For @= objects, the compiler never tries to interfere and insert
    61 %     constructor and destructor calls for that object. Copy constructor
    62 %     calls do not count, because the object is not the target of the copy
    63 %     constructor.
    64 
    65 % A constructor is declared with the name ?{}
    66 % + combines the look of C initializers with the precedent of ?() being
    67 %   the name for the function call operator
    68 % + it is possible to easily search for all constructors in a project
    69 %   and immediately know that a function is a constructor by seeing the
    70 %   name "?{}"
    71 
    72 % A destructor is declared with the name ^?{}
    73 % + name mirrors a constructor's name, with an extra symbol to
    74 %   distinguish it
    75 % - the symbol '~' cannot be used due to parsing conflicts with the
    76 %   unary '~' (bitwise negation) operator - this conflict exists because
    77 %   we want to allow users to write ^x{}; to destruct x, rather than
    78 %   ^?{}(&x);
    79 
    80 % The first argument of a constructor must be a pointer. The constructed
    81 % type is the base type of the pointer. E.g. void ?{}(T *) is a default
    82 % constructor for a T.
    83 % + can name the argument whatever you like, so not constrained by
    84 %   language keyword "this" or "self", etc.
    85 % - have to explicitly qualify all object members to initialize them
    86 %   (e.g. this->x = 0, rather than just x = 0)
    87 
    88 % Destructors can take arguments other than just the destructed pointer
    89 % * open research problem: not sure how useful this is
    90 
    91 % Pointer constructors
    92 % + can construct separately compiled objects (opaque types) [6]
    93 % + orthogonal design, follows directly from the definition of the first
    94 %   argument of a constructor
    95 % - may require copy constructor or move constructor (or equivalent)
    96 %   for correct implementation, which may not be obvious to everyone
    97 % + required feature for the prelude to specify as much behavior as possible
    98 %   (similar to pointer assignment operators in this respect)
    99 
    100 % Designations can only be used for C-style initialization
    101 % * designation for constructors is equivalent to designation for any
    102 %   general function call. Since a function prototype can be redeclared
    103 %   many times, with arguments named differently each time (or not at
    104 %   all!), this is considered to be an undesirable feature. We could
    105 %   construct some set of rules to allow this behaviour, but it is
    106 %   probably more trouble than it's worth, and no matter what we choose,
    107 %   it is not likely to be obvious to most people.
    108 
    109 % Constructing an anonymous member [7]
    110 % + same as with calling any other function on an anonymous member
    111 %   (implicit conversion by the compiler)
    112 % - may be some cases where this is ambiguous => clarify with a cast
    113 %   (try to design APIs to avoid sharing function signatures between
    114 %   composed types to avoid this)
    115 
    116 % Default Constructors and Destructors are called implicitly
    117 % + cannot forget to construct or destruct an object
    118 % - requires special syntax to specify that an object is not to be
    119 %   constructed (@=)
    120 % * an object will not be implicitly constructed OR destructed if
    121 %   explicitly initialized like a C object (@= syntax)
    122 % * an object will be destructed if there are no constructors in scope
    123 %   (even though it is initialized like a C object) [8]
    124 
    125 % An object which changes from POD type to non POD type will not change
    126 % the semantics of a type containing it by composition
    127 % * That is, constructors will not be regenerated at the point where
    128 %   an object changes from POD type to non POD type, because this could
    129 %   cause a cascade of constructors being regenerated for many other
    130 %   types. Further, there is precedence for this behaviour in other
    131 %   facets of Cforall's design, such as how nested functions interact.
    132 % * This behaviour can be simplified in a language without declaration
    133 %   before use, because a type can be classified as POD or non POD
    134 %   (rather than potentially changing between the two at some point) at
    135 %   at the global scope (which is likely the most common case)
    136 % * [9]
    137 
    138 % Changes to polymorphic type classes
    139 % * dtype and ftype remain the same
    140 % * forall(otype T) is currently essentially the same as
    141 %   forall(dtype T | { @size(T); void ?=?(T *, T); }).
    142 %   The big addition is that you can declare an object of type T, rather
    143 %   than just a pointer to an object of type T since you know the size,
    144 %   and you can assign into a T.
    145 %   * this definition is changed to add default constructor and
    146 %     destructor declarations, to remain consistent with what type meant
    147 %     before the introduction of constructors and destructors.
    148 %     * that is, forall(type T) is now essentially the same as
    149 %       forall(dtype T | { @size(T); void ?=?(T *, T);
    150 %                          void ?{}(T *); void ^?{}(T *); })
    151 %     + this is required to make generic types work correctly in
    152 %       polymorphic functions
    153 %     ? since declaring a constructor invalidates the autogenerated
    154 %       routines, it is possible for a type to have constructors, but
    155 %       not default constructors. That is, it might be the case that
    156 %       you want to write a polymorphic function for a type which has
    157 %       a size, but non-default constructors? Some options:
    158 %       * declaring a constructor as a part of the assertions list for
    159 %         a type declaration invalidates the default, so
    160 %         forall(otype T | { void ?{}(T *, int); })
    161 %         really means
    162 %         forall(dtype T | { @size(T); void ?=?(T *, T);
    163 %                            void ?{}(T *, int); void ^?{}(T *); })
    164 %       * force users to fully declare the assertions list like the
    165 %         above in this case (this seems very undesirable)
    166 %       * add another type class with the current desugaring of type
    167 %         (just size and assignment)
    168 %       * provide some way of subtracting from an existing assertions
    169 %         list (this might be useful to have in general)
    170 
    171 % Implementation issues:
    172 % Changes to prelude/autogen or built in defaults?
    173 % * pointer ctors/dtors [prelude]
    174 %   * other pointer type routines are declared in the prelude, and this
    175 %     doesn't seem like it should be any different
    176 % * basic type ctors/dtors [prelude]
    177 %   * other basic type routines are declared in the prelude, and this
    178 %     doesn't seem like it should be any different
    179 % ? aggregate types [undecided, but leaning towards autogenerate]
    180 %   * prelude
    181 %     * routines specific to aggregate types cannot be predeclared in
    182 %       the prelude because we don't know the name of every
    183 %       aggregate type in the entire program
    184 %   * autogenerate
    185 %     + default assignment operator is already autogenerated for
    186 %       aggregate types
    187 %       * this seems to lead us in the direction of autogenerating,
    188 %         because we may have a struct which contains other objects
    189 %         that require construction [10]. If we choose not to
    190 %         autogenerate in this case, then objects which are part of
    191 %         other objects by composition will not be constructed unless
    192 %         a constructor for the outer type is explicitly defined
    193 %       * in this case, we would always autogenerate the appropriate
    194 %         constructor(s) for an aggregate type, but just like with
    195 %         basic types, pointer types, and enum types, the constructor
    196 %         call can be elided when when it is not necessary.
    197 %     + constructors will have to be explicitly autogenerated
    198 %       in the case where they are required for a polymorphic function,
    199 %       when no user defined constructor is in scope, which may make it
    200 %       easiest to always autogenerate all appropriate constructors
    201 %     - n+2 constructors would have to be generated for a POD type
    202 %       * one constructor for each number of valid arguments [0, n],
    203 %         plus the copy constructor
    204 %         * this is taking a simplified approach: in C, it is possible
    205 %           to omit the enclosing braces in a declaration, which would
    206 %           lead to a combinatorial explosion of generated constructors.
    207 %           In the interest of keeping things tractable, Cforall may be
    208 %           incompatible with C in this case. [11]
    209 %       * for non-POD types, only autogenerate the default and copy
    210 %         constructors
    211 %       * alternative: generate only the default constructor and
    212 %         special case initialization for any other constructor when
    213 %         only the autogenerated one exists
    214 %         - this is not very sensible, as by the previous point, these
    215 %           constructors may be needed for polymorphic functions
    216 %           anyway.
    217 %     - must somehow distinguish in resolver between autogenerated and
    218 %       user defined constructors (autogenerated should never be chosen
    219 %       when a user defined option exists [check first parameter], even
    220 %       if full signature differs) (this may also have applications
    221 %       to other autogenerated routines?)
    222 %     - this scheme does not naturally support designation (i.e. general
    223 %       functions calls do not support designation), thus these cases
    224 %       will have to be treated specially in either case
    225 %   * defaults
    226 %     * i.e. hardcode a new set of rules for some "appropriate" default
    227 %       behaviour for
    228 %     + when resolving an initialization expression, explicitly check to
    229 %       see if any constructors are in scope. If yes, attempt to resolve
    230 %       to a constructor, and produce an error message if a match is not
    231 %       found. If there are no constructors in scope, resolve to
    232 %       initializing each field individually (C-style)
    233 %     + does not attempt to autogenerate constructors for POD types,
    234 %       which can be seen as a space optimization for the program
    235 %       binary
    236 %     - as stated previously, a polymorphic routine may require these
    237 %       autogenerated constructors, so this doesn't seem like a big win,
    238 %       because this leads to more complicated logic and tracking of
    239 %       which constructors have already been generated
    240 %     - even though a constructor is not explicitly declared or used
    241 %       polymorphically, we might still need one for all uses of a
    242 %       struct (e.g. in the case of composition).
    243 %   * the biggest tradeoff in autogenerating vs. defaulting appears to
    244 %     be in where and how the special code to check if constructors are
    245 %     present is handled. It appears that there are more reasons to
    246 %     autogenerate than not.
    247 
    248 % --- examples
    249 % [1] As an example of using constructors polymorphically, consider a
    250 % slight modification on the foldl example I put on the mailing list a
    251 % few months ago:
    252 
    253 % context iterable(type collection, type element, type iterator) {
    254 %   void ?{}(iterator *, collection); // used to be makeIterator, but can
    255 %                             // idiomatically use constructor
    256 %   int hasNext(iterator);
    257 %   iterator ++?(iterator *);
    258 %   lvalue element *?(iterator);
    259 % };
    260 
    261 
    262 % forall(type collection, type element, type result, type iterator
    263 %   | iterable(collection, element, iterator))
    264 % result foldl(collection c, result acc,
    265 %     result (*reduce)(result, element)) {
    266 %   iterator it = { c };
    267 %   while (hasNext(it)) {
    268 %     acc = reduce(acc, *it);
    269 %     ++it;
    270 %   }
    271 %   return acc;
    272 % }
    273 
    274 % Now foldl makes use of the knowledge that the iterator type has a
    275 % single argument constructor which takes the collection to iterate
    276 % over. This pattern allows polymorphic code to look more natural
    277 % (constructors are generally preferred to named initializer/creation
    278 % routines, e.g. "makeIterator")
    279 
    280 % [2] An example of some potentially dangerous code that we don't want
    281 % to let easily slip through the cracks - if this is really what you
    282 % want, then use @= syntax for the second declaration to quiet the
    283 % compiler.
    284 
    285 % struct A { int x, y, z; }
    286 % ?{}(A *, int);
    287 % ?{}(A *, int, int, int);
    288 
    289 % A a1 = { 1 };         // uses ?{}(A *, int);
    290 % A a2 = { 2, 3 };      // C-style initialization -> no invariants!
    291 % A a3 = { 4, 5, 6 };   // uses ?{}(A *, int, int, int);
    292 
    293 % [3] Since @= syntax creates a C object (essentially a POD, as far as
    294 % the compiler is concerned), the object will not be destructed
    295 % implicitly when it leaves scope, nor will it be copy constructed when
    296 % it is returned. In this case, a memcpy should be equivalent to a move.
    297 
    298 % // Box.h
    299 % struct Box;
    300 % void ?{}(Box **, int};
    301 % void ^?{}(Box **);
    302 % Box * make_fortytwo();
    303 
    304 % // Box.cfa
    305 % Box * make_fortytwo() {
    306 %   Box *b @= {};
    307 %   (&b){ 42 }; // construct explicitly
    308 %   return b; // no destruction, essentially a move?
    309 % }
    310 
    311 % [4] Cforall's typesafe malloc can be composed with constructor
    312 % expressions. It is possible for a user to define their own functions
    313 % similar to malloc and achieve the same effects (e.g. Aaron's example
    314 % of an arena allocator)
    315 
    316 % // CFA malloc
    317 % forall(type T)
    318 % T * malloc() { return (T *)malloc(sizeof(T)); }
    319 
    320 % struct A { int x, y, z; };
    321 % void ?{}(A *, int);
    322 
    323 % int foo(){
    324 %   ...
    325 %   // desugars to:
    326 %   // A * a = ?{}(malloc(), 123);
    327 %   A * a = malloc() { 123 };
    328 %   ...
    329 % }
    330 
    331 % [5] Aaron's example of combining function calls with constructor
    332 % syntax to perform an operation similar to C++'s std::vector::emplace
    333 % (i.e. to construct a new element in place, without the need to
    334 % copy)
    335 
    336 % forall(type T)
    337 % struct vector {
    338 %   T * elem;
    339 %   int len;
    340 %   ...
    341 % };
    342 
    343 % ...
    344 % forall(type T)
    345 % T * vector_new(vector(T) * v) {
    346 %   // reallocate if needed
    347 %   return &v->elem[len++];
    348 % }
    349 
    350 % int main() {
    351 %   vector(int) * v = ...
    352 %   vector_new(v){ 42 };  // add element to the end of vector
    353 % }
    354 
    355 % [6] Pointer Constructors. It could be useful to use the existing
    356 % constructor syntax even more uniformly for ADTs. With this, ADTs can
    357 % be initialized in the same manor as any other object in a polymorphic
    358 % function.
    359 
    360 % // vector.h
    361 % forall(type T) struct vector;
    362 % forall(type T) void ?{}(vector(T) **);
    363 % // adds an element to the end
    364 % forall(type T) vector(T) * ?+?(vector(T) *, T);
    365 
    366 % // vector.cfa
    367 % // don't want to expose the implementation to the user and/or don't
    368 % // want to recompile the entire program if the struct definition
    369 % // changes
    370 
    371 % forall(type T) struct vector {
    372 %   T * elem;
    373 %   int len;
    374 %   int capacity;
    375 % };
    376 
    377 % forall(type T) void resize(vector(T) ** v) { ... }
    378 
    379 % forall(type T) void ?{}(vector(T) ** v) {
    380 %   vector(T) * vect = *v = malloc();
    381 %   vect->capacity = 10;
    382 %   vect->len = 0;
    383 %   vect->elem = malloc(vect->capacity);
    384 % }
    385 
    386 % forall(type T) vector(T) * ?+?(vector(T) *v, T elem) {
    387 %   if (v->len == v->capacity) resize(&v);
    388 %   v->elem[v->len++] = elem;
    389 % }
    390 
    391 % // main.cfa
    392 % #include "adt.h"
    393 % forall(type T | { T ?+?(T, int); }
    394 % T sumRange(int lower, int upper) {
    395 %   T x;    // default construct
    396 %   for (int i = lower; i <= upper; i++) {
    397 %     x = x + i;
    398 %   }
    399 %   return x;
    400 % }
    401 
    402 % int main() {
    403 %   vector(int) * numbers = sumRange(1, 10);
    404 %   // numbers is now a vector containing [1..10]
    405 
    406 %   int sum = sumRange(1, 10);
    407 %   // sum is now an int containing the value 55
    408 % }
    409 
    410 % [7] The current proposal is to use the plan 9 model of inheritance.
    411 % Under this model, all of the members of an unnamed struct instance
    412 % become members of the containing struct. In addition, an object
    413 % can be passed as an argument to a function expecting one of its
    414 % base structs.
    415 
    416 % struct Point {
    417 %   double x;
    418 %   double y;
    419 % };
    420 
    421 % struct ColoredPoint {
    422 %   Point;        // anonymous member (no identifier)
    423 %                 // => a ColoredPoint has an x and y of type double
    424 %   int color;
    425 % };
    426 
    427 % ColoredPoint cp = ...;
    428 % cp.x = 10.3;    // x from Point is accessed directly
    429 % cp.color = 0x33aaff; // color is accessed normally
    430 % foo(cp);        // cp can be used directly as a Point
    431 
    432 % void ?{}(Point *p, double x, double y) {
    433 %   p->x = x;
    434 %   p->y = y;
    435 % }
    436 
    437 % void ?{}(ColoredPoint *cp, double x, double y, int color) {
    438 %   (&cp){ x, y };  // unambiguous, no ?{}(ColoredPoint*,double,double)
    439 %   cp->color = color;
    440 % }
    441 
    442 % struct Size {
    443 %   double width;
    444 %   double height;
    445 % };
    446 
    447 % void ?{}(Size *s, double w, double h) {
    448 %   p->width = w;
    449 %   p->height = h;
    450 % }
    451 
    452 % struct Foo {
    453 %   Point;
    454 %   Size;
    455 % }
    456 
    457 % ?{}(Foo &f, double x, double y, double w, double h) {
    458 %   // (&F,x,y) is ambiguous => is it ?{}(Point*,double,double) or
    459 %   // ?{}(Size*,double,double)? Solve with a cast:
    460 %   ((Point*)&F){ x, y };
    461 %   ((Size*)&F){ w, h };
    462 % }
    463 
    464 % [8] Destructors will be called on objects that were not constructed.
    465 
    466 % struct A { ... };
    467 % ^?{}(A *);
    468 % {
    469 %   A x;
    470 %   A y @= {};
    471 % } // x is destructed, even though it wasn't constructed
    472 %   // y is not destructed, because it is explicitly a C object
    473 
    474 
    475 % [9] A type's constructor is generated at declaration time using
    476 % current information about an object's members. This is analogous to
    477 % the treatment of other operators. For example, an object's assignment
    478 % operator will not change to call the override of a member's assignment
    479 % operator unless the object's assignment is also explicitly overridden.
    480 % This problem can potentially be treated differently in Do, since each
    481 % compilation unit is passed over at least twice (once to gather
    482 % symbol information, once to generate code - this is necessary to
    483 % achieve the "No declarations" goal)
    484 
    485 % struct A { ... };
    486 % struct B { A x; };
    487 % ...
    488 % void ?{}(A *);  // from this point on, A objects will be constructed
    489 % B b1;           // b1 and b1.x are both NOT constructed, because B
    490 %                 // objects are not constructed
    491 % void ?{}(B *);  // from this point on, B objects will be constructed
    492 % B b2;           // b2 and b2.x are both constructed
    493 
    494 % struct C { A x; };
    495 % // implicit definition of ?{}(C*), because C is not a POD type since
    496 % // it contains a non-POD type by composition
    497 % C c;            // c and c.x are both constructed
    498 
    499 % [10] Requiring construction by composition
    500 
    501 % struct A {
    502 %   ...
    503 % };
    504 
    505 % // declared ctor disables default c-style initialization of
    506 % // A objects; A is no longer a POD type
    507 % void ?{}(A *);
    508 
    509 % struct B {
    510 %   A x;
    511 % };
    512 
    513 % // B objects can not be C-style initialized, because A objects
    514 % // must be constructed => B objects are transitively not POD types
    515 % B b; // b.x must be constructed, but B is not constructible
    516 %      // => must autogenerate ?{}(B *) after struct B definition,
    517 %      // which calls ?{}(&b.x)
    518 
    519 % [11] Explosion in the number of generated constructors, due to strange
    520 % C semantics.
    521 
    522 % struct A { int x, y; };
    523 % struct B { A u, v, w; };
    524 
    525 % A a = { 0, 0 };
    526 
    527 % // in C, you are allowed to do this
    528 % B b1 = { 1, 2, 3, 4, 5, 6 };
    529 % B b2 = { 1, 2, 3 };
    530 % B b3 = { a, a, a };
    531 % B b4 = { a, 5, 4, a };
    532 % B b5 = { 1, 2, a, 3 };
    533 
    534 % // we want to disallow b1, b2, b4, and b5 in Cforall.
    535 % // In particular, we will autogenerate these constructors:
    536 % void ?{}(A *);             // default/0 parameters
    537 % void ?{}(A *, int);        // 1 parameter
    538 % void ?{}(A *, int, int);   // 2 parameters
    539 % void ?{}(A *, const A *);  // copy constructor
    540 
    541 % void ?{}(B *);             // default/0 parameters
    542 % void ?{}(B *, A);          // 1 parameter
    543 % void ?{}(B *, A, A);       // 2 parameters
    544 % void ?{}(B *, A, A, A);    // 3 parameters
    545 % void ?{}(B *, const B *);  // copy constructor
    546 
    547 % // we will not generate constructors for every valid combination
    548 % // of members in C. For example, we will not generate
    549 % void ?{}(B *, int, int, int, int, int, int);   // b1 would need this
    550 % void ?{}(B *, int, int, int);                  // b2 would need this
    551 % void ?{}(B *, A, int, int, A);                 // b4 would need this
    552 % void ?{}(B *, int, int, A, int);               // b5 would need this
    553 % // and so on
    554 
    555 
    556 
    557 % TODO: talk somewhere about compound literals?
    558 
    5598Since \CFA is a true systems language, it does not provide a garbage collector.
    560 As well, \CFA is not an object-oriented programming language, i.e. structures cannot have routine members.
     9As well, \CFA is not an object-oriented programming language, \ie, structures cannot have routine members.
    56110Nevertheless, one important goal is to reduce programming complexity and increase safety.
    56211To that end, \CFA provides support for implicit pre/post-execution of routines for objects, via constructors and destructors.
    56312
    564 % TODO: this is old. remove or refactor
    565 % Manual resource management is difficult.
    566 % Part of the difficulty results from not having any guarantees about the current state of an object.
    567 % 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.
    568 
    569 % 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.
    570 % 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.
    571 % Constructors and destructors can help to simplify resource management when used in a disciplined way.
    572 % In particular, when all resources are acquired in a constructor, and all resources are released in a destructor, no resource leaks are possible.
    573 % This pattern is a popular idiom in several languages, such as \CC, known as RAII (Resource Acquisition Is Initialization).
    574 
    57513This chapter details the design of constructors and destructors in \CFA, along with their current implementation in the translator.
    576 Generated code samples have been edited to provide comments for clarity and to save on space.
     14Generated code samples have been edited for clarity and brevity.
    57715
    57816\section{Design Criteria}
     
    59230Next, @x@ is assigned the value of @y@.
    59331In the last line, @z@ is implicitly initialized to 0 since it is marked @static@.
    594 The key difference between assignment and initialization being that assignment occurs on a live object (i.e. an object that contains data).
     32The key difference between assignment and initialization being that assignment occurs on a live object (\ie, an object that contains data).
    59533It is important to note that this means @x@ could have been used uninitialized prior to being assigned, while @y@ could not be used uninitialized.
    596 Use of uninitialized variables yields undefined behaviour, which is a common source of errors in C programs. % TODO: *citation*
    597 
    598 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.
    599 Many C compilers give good warnings most of the time, but they cannot in all cases.
    600 \begin{cfacode}
    601 int f(int *);  // never reads the parameter, only writes
    602 int g(int *);  // reads the parameter - expects an initialized variable
     34Use of uninitialized variables yields undefined behaviour, which is a common source of errors in C programs.
     35
     36Initialization of a declaration is strictly optional, permitting uninitialized variables to exist.
     37Furthermore, declaration initialization is limited to expressions, so there is no way to insert arbitrary code before a variable is live, without delaying the declaration.
     38Many C compilers give good warnings for uninitialized variables most of the time, but they cannot in all cases.
     39\begin{cfacode}
     40int f(int *);  // output parameter: never reads, only writes
     41int g(int *);  // input parameter: never writes, only reads,
     42               // so requires initialized variable
    60343
    60444int x, y;
    60545f(&x);  // okay - only writes to x
    606 g(&y);  // will use y uninitialized
    607 \end{cfacode}
    608 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.
    609 
    610 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.
     46g(&y);  // uses y uninitialized
     47\end{cfacode}
     48Other 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.
     49
     50In C, constructors and destructors are often mimicked by providing routines that create and tear down objects, where the tear down function is typically only necessary if the type modifies the execution environment.
    61151\begin{cfacode}
    61252struct array_int {
     
    61454};
    61555struct array_int create_array(int sz) {
    616   return (struct array_int) { malloc(sizeof(int)*sz) };
     56  return (struct array_int) { calloc(sizeof(int)*sz) };
    61757}
    61858void destroy_rh(struct resource_holder * rh) {
     
    63474Furthermore, even with this idiom it is easy to make mistakes, such as forgetting to destroy an object or destroying it multiple times.
    63575
    636 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.
     76A constructor provides a way of ensuring that the necessary aspects of object initialization is performed, from setting up invariants to providing compile- and run-time checks for appropriate initialization parameters.
    63777This 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.
    63878Since 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.
    63979
    64080In \CFA, a constructor is a function with the name @?{}@.
     81Like other operators in \CFA, the name represents the syntax used to call the constructor, \eg, @struct S = { ... };@.
    64182Every 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).
    64283The @this@ parameter must have a pointer type, whose base type is the type of object that the function constructs.
     
    65596
    65697In C, if the user creates an @Array@ object, the fields @data@ and @len@ are uninitialized, unless an explicit initializer list is present.
    657 It is the user's responsibility to remember to initialize both of the fields to sensible values.
     98It 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.
    65899In \CFA, the user can define a constructor to handle initialization of @Array@ objects.
    659100
     
    671112This 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.
    672113This particular form of constructor is called the \emph{default constructor}, because it is called on an object defined without an initializer.
    673 In other words, a default constructor is a constructor that takes a single argument, the @this@ parameter.
    674 
    675 In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}!.
    676 A destructor for the @Array@ type can be defined as such.
     114In other words, a default constructor is a constructor that takes a single argument: the @this@ parameter.
     115
     116In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}! and it takes only one argument.
     117A destructor for the @Array@ type can be defined as:
    677118\begin{cfacode}
    678119void ^?{}(Array * arr) {
     
    680121}
    681122\end{cfacode}
    682 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.
     123The destructor is automatically called at deallocation for all objects of type @Array@.
     124Hence, the memory associated with an @Array@ is automatically freed when the object's lifetime ends.
    683125The exact guarantees made by \CFA with respect to the calling of destructors are discussed in section \ref{sub:implicit_dtor}.
    684126
     
    691133\end{cfacode}
    692134By the previous definition of the default constructor for @Array@, @x@ and @y@ are initialized to valid arrays of length 10 after their respective definitions.
    693 On line 3, @z@ is initialized with the value of @x@, while on line @4@, @y@ is assigned the value of @x@.
     135On line 2, @z@ is initialized with the value of @x@, while on line 3, @y@ is assigned the value of @x@.
    694136The 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.
    695137In particular, these cases cannot be handled the same way because in the former case @z@ does not currently own an array, while @y@ does.
     
    712154The first function is called a \emph{copy constructor}, because it constructs its argument by copying the values from another object of the same type.
    713155The second function is the standard copy-assignment operator.
    714 These four functions are special in that they control the state of most objects.
     156The four functions (default constructor, destructor, copy constructor, and assignment operator) are special in that they safely control the state of most objects.
    715157
    716158It is possible to define a constructor that takes any combination of parameters to provide additional initialization options.
    717 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.
     159For example, a reasonable extension to the array type would be a constructor that allocates the array to a given initial capacity and initializes the elements of the array to a given @fill@ value.
    718160\begin{cfacode}
    719161void ?{}(Array * arr, int capacity, int fill) {
     
    725167}
    726168\end{cfacode}
     169
    727170In \CFA, constructors are called implicitly in initialization contexts.
    728171\begin{cfacode}
    729172Array x, y = { 20, 0xdeadbeef }, z = y;
    730173\end{cfacode}
    731 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.
    732 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.
     174Constructor 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.
     175One downside of reusing C initialization syntax is that it is not 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 in the program.
    733176
    734177This example generates the following code
     
    748191Destructors are implicitly called in reverse declaration-order so that objects with dependencies are destructed before the objects they are dependent on.
    749192
    750 \subsection{Syntax}
    751 \label{sub:syntax} % TODO: finish this section
     193\subsection{Calling Syntax}
     194\label{sub:syntax}
    752195There are several ways to construct an object in \CFA.
    753196As previously introduced, every variable is automatically constructed at its definition, which is the most natural way to construct an object.
     
    773216A * y = malloc();  // copy construct: ?{}(&y, malloc())
    774217
    775 ?{}(&x);    // explicit construct x
    776 ?{}(y, x);  // explit construct y from x
    777 ^?{}(&x);   // explicit destroy x
     218?{}(&x);    // explicit construct x, second construction
     219?{}(y, x);  // explit construct y from x, second construction
     220^?{}(&x);   // explicit destroy x, in different order
    778221^?{}(y);    // explicit destroy y
    779222
     
    781224// implicit ^?{}(&x);
    782225\end{cfacode}
    783 Calling a constructor or destructor directly is a flexible feature that allows complete control over the management of a piece of storage.
     226Calling a constructor or destructor directly is a flexible feature that allows complete control over the management of storage.
    784227In particular, constructors double as a placement syntax.
    785228\begin{cfacode}
     
    803246\end{cfacode}
    804247Finally, constructors and destructors support \emph{operator syntax}.
    805 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.
     248Like other operators in \CFA, the function name mirrors the use-case, in that the question marks are placeholders for the first $N$ arguments.
     249This syntactic form is similar to the new initialization syntax in \CCeleven, except that it is used in expression contexts, rather than declaration contexts.
    806250\begin{cfacode}
    807251struct A { ... };
     
    822266Destructor operator syntax is actually an statement, and requires parentheses for symmetry with constructor syntax.
    823267
     268One of these three syntactic forms should appeal to either C or \CC programmers using \CFA.
     269
     270\subsection{Constructor Expressions}
     271In \CFA, it is possible to use a constructor as an expression.
     272Like other operators, the function name @?{}@ matches its operator syntax.
     273For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result.
     274A key example for this capability is the use of constructor expressions to initialize the result of a call to @malloc@.
     275\begin{cfacode}
     276struct X { ... };
     277void ?{}(X *, double);
     278X * x = malloc(){ 1.5 };
     279\end{cfacode}
     280In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@.
     281If 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.
     282\begin{cfacode}
     283X * x = malloc();
     284x{ 1.5 };
     285\end{cfacode}
     286Not 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.
     287This feature is implemented via a transformation producing the value of the first argument of the constructor, since constructors do not themselves have a return value.
     288Since 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.
     289The previous example generates the following code.
     290\begin{cfacode}
     291struct X *_tmp_ctor;
     292struct X *x = ?{}(  // construct result of malloc
     293  _tmp_ctor=malloc_T( // store result of malloc
     294    sizeof(struct X),
     295    _Alignof(struct X)
     296  ),
     297  1.5
     298), _tmp_ctor; // produce constructed result of malloc
     299\end{cfacode}
     300It 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.
     301
     302It should be noted that while it is possible to use operator syntax with destructors, destructors invalidate their argument, thus operator syntax with destructors is a statement and does not produce a value.
     303
    824304\subsection{Function Generation}
    825 In \CFA, every type is defined to have the core set of four functions described previously.
     305In \CFA, every type is defined to have the core set of four special functions described previously.
    826306Having 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.
    827307In addition to simplifying the definition of the language, it also simplifies the analysis that the translator must perform.
     
    833313There are several options for user-defined types: structures, unions, and enumerations.
    834314To aid in ease of use, the standard set of four functions is automatically generated for a user-defined type after its definition is completed.
    835 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.
     315By 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.
    836316
    837317The generated functions for enumerations are the simplest.
    838 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.
    839 % TODO: examples for enums
     318Since enumerations in C are essentially just another integral type, the generated functions behave in the same way that the built-in functions for the basic types work.
    840319For example, given the enumeration
    841320\begin{cfacode}
     
    850329}
    851330void ?{}(enum Colour *_dst, enum Colour _src){
    852   (*_dst)=_src;  // bitwise copy
     331  *_dst=_src;  // bitwise copy
    853332}
    854333void ^?{}(enum Colour *_dst){
     
    856335}
    857336enum Colour ?=?(enum Colour *_dst, enum Colour _src){
    858   return (*_dst)=_src; // bitwise copy
     337  return *_dst=_src; // bitwise copy
    859338}
    860339\end{cfacode}
    861340In the future, \CFA will introduce strongly-typed enumerations, like those in \CC.
    862 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.
     341The existing generated routines are sufficient to express this restriction, since they are currently set up to take in values of that enumeration type.
    863342Changes 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@.
    864 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.
     343In 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.
    865344
    866345For structures, the situation is more complicated.
    867 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$@.
    868 That is, a default constructor for @S@ default constructs the members of @S@, the copy constructor with copy construct them, and so on.
    869 For example given the struct definition
     346Given 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$@.
     347That is, a default constructor for @S@ default constructs the members of @S@, the copy constructor copy constructs them, and so on.
     348For example, given the structure definition
    870349\begin{cfacode}
    871350struct A {
     
    893372}
    894373\end{cfacode}
    895 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.
     374It is important to note that the destructors are called in reverse declaration order to prevent conflicts in the event there are dependencies among members.
    896375
    897376In addition to the standard set, a set of \emph{field constructors} is also generated for structures.
    898 The field constructors are constructors that consume a prefix of the struct's member list.
     377The field constructors are constructors that consume a prefix of the structure's member-list.
    899378That 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.
    900 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 }@.
     379The addition of field constructors allows structures in \CFA to be used naturally in the same ways as used in C (\ie, to initialize any prefix of the structure), \eg, @A a0 = { b }, a1 = { b, c }@.
    901380Extending the previous example, the following constructors are implicitly generated for @A@.
    902381\begin{cfacode}
     
    911390\end{cfacode}
    912391
    913 For unions, the default constructor and destructor do nothing, as it is not obvious which member if any should be constructed.
     392For unions, the default constructor and destructor do nothing, as it is not obvious which member, if any, should be constructed.
    914393For copy constructor and assignment operations, a bitwise @memcpy@ is applied.
    915394In 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.
    916 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.
     395An alternative 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.
    917396This approach ultimately feels subtle and unsafe.
    918397Another option is to, like \CC, disallow unions from containing members that are themselves managed types.
     
    947426
    948427% 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
    949 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.
     428In \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.
    950429This restriction could easily be added into \CFA once \emph{deleted} functions are added.
    951430
    952431\subsection{Using Constructors and Destructors}
    953 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.
     432Implicitly generated constructor and destructor calls ignore the outermost type qualifiers, \eg @const@ and @volatile@, on a type by way of a cast on the first argument to the function.
    954433For example,
    955434\begin{cfacode}
     
    970449Here, @&s@ and @&s2@ are cast to unqualified pointer types.
    971450This mechanism allows the same constructors and destructors to be used for qualified objects as for unqualified objects.
    972 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.
     451This rule applies only to implicitly generated constructor calls.
     452Hence, explicitly re-initializing qualified objects with a constructor requires an explicit cast.
     453
     454As discussed in Section \ref{sub:c_background}, compound literals create unnamed objects.
     455This mechanism can continue to be used seamlessly in \CFA with managed types to create temporary objects.
     456The 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.
     457For example,
     458\begin{cfacode}
     459struct A { int x; };
     460void ?{}(A *, int, int);
     461{
     462  int x = (A){ 10, 20 }.x;
     463}
     464\end{cfacode}
     465is equivalent to
     466\begin{cfacode}
     467struct A { int x, y; };
     468void ?{}(A *, int, int);
     469{
     470  A _tmp;
     471  ?{}(&_tmp, 10, 20);
     472  int x = _tmp.x;
     473  ^?{}(&tmp);
     474}
     475\end{cfacode}
    973476
    974477Unlike \CC, \CFA provides an escape hatch that allows a user to decide at an object's definition whether it should be managed or not.
     
    984487A a2 @= { 0 };  // unmanaged
    985488\end{cfacode}
    986 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.
    987 Instead, @a2->x@ is initialized to @0@ as if it were a C object, due to the explicit initializer.
    988 Existing constructors are ignored when \ateq is used, so that any valid C initializer is able to initialize the object.
    989 
    990 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.
     489In 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.
     490Instead, @a2->x@ is initialized to @0@ as if it were a C object, because of the explicit initializer.
     491
     492In addition to freedom, \ateq provides a simple path for migrating legacy C code to \CFA, in that objects can be moved from C-style initialization to \CFA gradually and individually.
    991493It 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.
    992494It is recommended that most objects be managed by sensible constructors and destructors, except where absolutely necessary.
    993495
    994 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.
    995 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.
    996 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??
     496When 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.
     497Furthermore, if the user declares any constructor, then the intrinsic/generated default constructor is also hidden, precluding default construction.
     498These 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++}.
    997499\begin{cfacode}
    998500struct S { int x, y; };
     
    1001503  S s0, s1 = { 0 }, s2 = { 0, 2 }, s3 = s2;  // okay
    1002504  {
    1003     void ?{}(S * s, int i) { s->x = i*2; }
    1004     S s4;  // error
    1005     S s5 = { 3 };  // okay
    1006     S s6 = { 4, 5 };  // error
     505    void ?{}(S * s, int i) { s->x = i*2; } // locally hide autogen ctors
     506    S s4;  // error, no default constructor
     507    S s5 = { 3 };  // okay, local constructor
     508    S s6 = { 4, 5 };  // error, no field constructor
    1007509    S s7 = s5; // okay
    1008510  }
     
    1012514In 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.
    1013515
    1014 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.
     516When defining a constructor or destructor for a structure @S@, any members that are not explicitly constructed or destructed are implicitly constructed or destructed automatically.
    1015517If an explicit call is present, then that call is taken in preference to any implicitly generated call.
    1016 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.
     518A consequence of this rule is that it is possible, unlike \CC, to precisely control the order of construction and destruction of sub-objects on a per-constructor basis, whereas in \CC sub-object initialization and destruction is always performed based on the declaration order.
    1017519\begin{cfacode}
    1018520struct A {
     
    1033535}
    1034536\end{cfacode}
    1035 Finally, it is illegal for a subobject to be explicitly constructed for the first time after it is used for the first time.
     537Finally, it is illegal for a sub-object to be explicitly constructed for the first time after it is used for the first time.
    1036538If the translator cannot be reasonably sure that an object is constructed prior to its first use, but is constructed afterward, an error is emitted.
    1037 More specifically, the translator searches the body of a constructor to ensure that every subobject is initialized.
     539More specifically, the translator searches the body of a constructor to ensure that every sub-object is initialized.
    1038540\begin{cfacode}
    1039541void ?{}(A * a, double x) {
     
    1042544}
    1043545\end{cfacode}
    1044 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).
     546However, if the translator sees a sub-object used within the body of a constructor, but does not see a constructor call that uses the sub-object 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).
    1045547\begin{cfacode}
    1046548void ?{}(A * a) {
     
    1058560} // z, y, w implicitly destructed, in this order
    1059561\end{cfacode}
    1060 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).
     562If 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.
    1061563To override this rule, \ateq can be used to force the translator to trust the programmer's discretion.
    1062564This form of \ateq is not yet implemented.
     
    1064566Despite great effort, some forms of C syntax do not work well with constructors in \CFA.
    1065567In 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.
    1066 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.
    1067 Furthermore, a function prototype can be repeated an arbitrary number of times, each time using different names.
    1068568\begin{cfacode}
    1069569// all legal forward declarations in C
     
    1076576f(b:10, a:20, c:30);  // which parameter is which?
    1077577\end{cfacode}
     578In 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.
     579Furthermore, a function prototype can be repeated an arbitrary number of times, each time using different names.
    1078580As 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.
    1079 % 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.
    1080 
    1081 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.
     581
     582\begin{sloppypar}
     583In addition, constructor calls do not support unnamed nesting.
     584\begin{cfacode}
     585struct B { int x; };
     586struct C { int y; };
     587struct A { B b; C c; };
     588void ?{}(A *, B);
     589void ?{}(A *, C);
     590
     591A a = {
     592  { 10 },  // construct B? - invalid
     593};
     594\end{cfacode}
     595In C, nesting initializers means that the programmer intends to initialize sub-objects with the nested initializers.
     596The reason for this omission is to both simplify the mental model for using constructors, and to make initialization simpler for the expression resolver.
     597If 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.
     598That 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@.
     599In 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.
     600\end{sloppypar}
     601
     602More precisely, constructor calls cannot have a nesting depth greater than the number of array dimensions in the type of the initialized object, plus one.
    1082603For example,
    1083604\begin{cfacode}
     
    1091612  { {14 }, { 15 } }   // a2[1]
    1092613};
    1093 A a3[4] = {
    1094   { { 11 }, { 12 } },  // error
     614A a3[4] = { // 1 dimension => max depth 2
     615  { { 11 }, { 12 } },  // error, three levels deep
    1095616  { 80 }, { 90 }, { 100 }
    1096617}
    1097618\end{cfacode}
    1098 % TODO: in CFA if the array dimension is empty, no object constructors are added -- need to fix this.
    1099619The body of @A@ has been omitted, since only the constructor interfaces are important.
    1100 In C, having a greater nesting depth means that the programmer intends to initialize subobjects with the nested initializer.
    1101 The reason for this omission is to both simplify the mental model for using constructors, and to make initialization simpler for the expression resolver.
    1102 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.
    1103 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)@.
    1104 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.
     620
    1105621It should be noted that unmanaged objects can still make use of designations and nested initializers in \CFA.
     622It 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.
    1106623
    1107624\subsection{Implicit Destructors}
    1108625\label{sub:implicit_dtor}
    1109626Destructors are automatically called at the end of the block in which the object is declared.
    1110 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.
     627In addition to this, destructors are automatically called when statements manipulate control flow to leave a block in which the object is declared, \eg, with return, break, continue, and goto statements.
    1111628The example below demonstrates a simple routine with multiple return statements.
    1112629\begin{cfacode}
     
    1127644    if (i == 2) return; // destruct x, y
    1128645  } // destruct y
    1129 }
    1130 \end{cfacode}
    1131 
    1132 %% having this feels excessive, but it's here if necessary
    1133 % This procedure generates the following code.
    1134 % \begin{cfacode}
    1135 % void f(int i){
    1136 %   struct A x;
    1137 %   ?{}(&x);
    1138 %   {
    1139 %     struct A y;
    1140 %     ?{}(&y);
    1141 %     {
    1142 %       struct A z;
    1143 %       ?{}(&z);
    1144 %       {
    1145 %         if ((i==0)!=0) {
    1146 %           ^?{}(&z);
    1147 %           ^?{}(&y);
    1148 %           ^?{}(&x);
    1149 %           return;
    1150 %         }
    1151 %       }
    1152 %       if (((i==1)!=0) {
    1153 %           ^?{}(&z);
    1154 %           ^?{}(&y);
    1155 %           ^?{}(&x);
    1156 %           return ;
    1157 %       }
    1158 %       ^?{}(&z);
    1159 %     }
    1160 
    1161 %     if ((i==2)!=0) {
    1162 %       ^?{}(&y);
    1163 %       ^?{}(&x);
    1164 %       return;
    1165 %     }
    1166 %     ^?{}(&y);
    1167 %   }
    1168 
    1169 %   ^?{}(&x);
    1170 % }
    1171 % \end{cfacode}
     646} // destruct x
     647\end{cfacode}
    1172648
    1173649The next example illustrates the use of simple continue and break statements and the manner that they interact with implicit destructors.
     
    1183659\end{cfacode}
    1184660Since 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.
    1185 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.
    1186 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.
     661In the case where @i@ is @2@, the continue statement runs the loop update expression and attempts to begin the next iteration of the loop.
     662Since continue is a C statement, which does not understand destructors, it is transformed into a @goto@ statement that branches to the end of the loop, just before the block's destructors, to ensure that @x@ is destructed.
    1187663When @i@ is @3@, the break statement moves control to just past the end of the loop.
    1188 Like the previous case, a destructor call for @x@ is inserted just before the break statement.
    1189 
    1190 \CFA also supports labelled break and continue statements, which allow more precise manipulation of control flow.
    1191 Labelled break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure.
     664Unlike the previous case, the destructor for @x@ cannot be reused, so a destructor call for @x@ is inserted just before the break statement.
     665
     666\CFA also supports labeled break and continue statements, which allow more precise manipulation of control flow.
     667Labeled break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure.
    1192668\begin{cfacode}[emph={L1,L2}, emphstyle=\color{red}]
    1193669L1: for (int i = 0; i < 10; i++) {
    1194670  A x;
    1195   L2: for (int j = 0; j < 10; j++) {
     671  for (int j = 0; j < 10; j++) {
    1196672    A y;
    1197     if (j == 0) {
    1198       continue;    // destruct y
    1199     } else if (j == 1) {
    1200       break;       // destruct y
    1201     } else if (i == 1) {
     673    if (i == 1) {
    1202674      continue L1; // destruct y
    1203675    } else if (i == 2) {
     
    1208680\end{cfacode}
    1209681The statement @continue L1@ begins the next iteration of the outer for-loop.
    1210 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@.
    1211 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.
     682Since the semantics of continue require the loop update expression to execute, control branches to the 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@.
     683Break, on the other hand, requires jumping out of both loops, so the destructors for both @x@ and @y@ are generated and inserted before the @break L1@ statement.
    1212684
    1213685Finally, an example which demonstrates goto.
     
    1256728}
    1257729\end{cfacode}
    1258 Labelled break and continue are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely goverened by these rules.
     730All break and continue statements are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely governed by these rules.
    1259731
    1260732The next example demonstrates the error case.
     
    1273745
    1274746\subsection{Implicit Copy Construction}
     747\label{s:implicit_copy_construction}
    1275748When 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.
    1276749When a value is returned from a function, the copy constructor is called to pass the value back to the call site.
    1277 Exempt from these rules are intrinsic and builtin functions.
     750Exempt from these rules are intrinsic and built-in functions.
    1278751It 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.
    1279 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.
     752That is, since the parameter is not marked as an unmanaged object using \ateq, it is 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.
     753These semantics are important to bear in mind when using unmanaged objects, and could produce unexpected results when mixed with objects that are explicitly constructed.
    1280754\begin{cfacode}
    1281755struct A;
     
    1284758void ^?{}(A *);
    1285759
    1286 A f(A x) {
    1287   return x;
     760A identity(A x) { // pass by value => need local copy
     761  return x;       // return by value => make call-site copy
    1288762}
    1289763
    1290764A y, z @= {};
    1291 identity(y);
    1292 identity(z);
    1293 \end{cfacode}
    1294 Note that @z@ is copy constructed into a temporary variable to be passed as an argument, which is also destructed after the call.
    1295 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.
     765identity(y);  // copy construct y into x
     766identity(z);  // copy construct z into x
     767\end{cfacode}
     768Note that unmanaged argument @z@ is logically copy constructed into managed parameter @x@; however, the translator must copy construct into a temporary variable to be passed as an argument, which is also destructed after the call.
     769A compiler could by-pass the argument temporaries since it is in control of the calling conventions and knows exactly where the called-function's parameters live.
    1296770
    1297771This generates the following
    1298772\begin{cfacode}
    1299773struct A f(struct A x){
    1300   struct A _retval_f;
    1301   ?{}((&_retval_f), x);
     774  struct A _retval_f;    // return value
     775  ?{}((&_retval_f), x);  // copy construct return value
    1302776  return _retval_f;
    1303777}
    1304778
    1305779struct A y;
    1306 ?{}(&y);
    1307 struct A z = { 0 };
    1308 
    1309 struct A _tmp_cp1;     // argument 1
    1310 struct A _tmp_cp_ret0; // return value
    1311 _tmp_cp_ret0=f((?{}(&_tmp_cp1, y) , _tmp_cp1)), _tmp_cp_ret0;
    1312 ^?{}(&_tmp_cp_ret0);   // return value
    1313 ^?{}(&_tmp_cp1);       // argument 1
    1314 
    1315 struct A _tmp_cp2;     // argument 1
    1316 struct A _tmp_cp_ret1; // return value
    1317 _tmp_cp_ret1=f((?{}(&_tmp_cp2, z), _tmp_cp2)), _tmp_cp_ret1;
    1318 ^?{}(&_tmp_cp_ret1);   // return value
    1319 ^?{}(&_tmp_cp2);       // argument 1
     780?{}(&y);                 // default construct
     781struct A z = { 0 };      // C default
     782
     783struct A _tmp_cp1;       // argument 1
     784struct A _tmp_cp_ret0;   // return value
     785_tmp_cp_ret0=f(
     786  (?{}(&_tmp_cp1, y) , _tmp_cp1)  // argument is a comma expression
     787), _tmp_cp_ret0;         // return value for cascading
     788^?{}(&_tmp_cp_ret0);     // destruct return value
     789^?{}(&_tmp_cp1);         // destruct argument 1
     790
     791struct A _tmp_cp2;       // argument 1
     792struct A _tmp_cp_ret1;   // return value
     793_tmp_cp_ret1=f(
     794  (?{}(&_tmp_cp2, z), _tmp_cp2)  // argument is a common expression
     795), _tmp_cp_ret1;         // return value for cascading
     796^?{}(&_tmp_cp_ret1);     // destruct return value
     797^?{}(&_tmp_cp2);         // destruct argument 1
    1320798^?{}(&y);
    1321799\end{cfacode}
    1322800
    1323 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.
    1324 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.
     801A 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.
     802\begin{cfacode}
     803identity(z@);  // do not copy construct argument
     804               // - will copy construct/destruct return value
     805A@ identity_nocopy(A @ x) {  // argument not copy constructed or destructed
     806  return x;  // not copy constructed
     807             // return type marked @ => not destructed
     808}
     809\end{cfacode}
     810It 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.
     811
     812A known issue with this implementation is that the argument and return value temporaries are not guaranteed to have the same address for their entire lifetimes.
     813In the previous example, 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.
    1325814This approach works out most of the time, because typically destructors need to only access the fields of the object and recursively destroy.
    1326 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.
    1327 Thus is it not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program.
     815It 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.
     816Thus, it is currently not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program.
    1328817\begin{cfacode}
    1329818A * external_data[32];
     
    1341830  }
    1342831}
     832
     833A makeA() {
     834  A x;  // stores &x in external_data
     835  return x;
     836}
     837makeA();  // return temporary has a different address than x
     838// equivalent to:
     839//   A _tmp;
     840//   _tmp = makeA(), _tmp;
     841//   ^?{}(&_tmp);
    1343842\end{cfacode}
    1344843In the above example, a global array of pointers is used to keep track of all of the allocated @A@ objects.
    1345 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.
    1346 
    1347 This problem could be solved in the translator by mutating the function signatures so that the return value is moved into the parameter list.
     844Due 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, such as in @makeA@.
     845
     846This problem could be solved in the translator by changing the function signatures so that the return value is moved into the parameter list.
    1348847For example, the translator could restructure the code like so
    1349848\begin{cfacode}
     
    1363862\end{cfacode}
    1364863This transformation provides @f@ with the address of the return variable so that it can be constructed into directly.
    1365 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}.
    1366 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.
     864It is worth pointing out that this kind of signature rewriting already occurs in polymorphic functions that return by value, as discussed in \cite{Bilson03}.
     865A 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, \eg
    1367866\begin{cfacode}
    1368867struct A { int v; };
    1369 A x; // unmanaged
     868A x; // unmanaged, since only trivial constructors are available
    1370869{
    1371870  void ?{}(A * a) { ... }
     
    1375874A z; // unmanaged
    1376875\end{cfacode}
    1377 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.
     876Hence 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.
    1378877Even 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.
    1379 Furthermore, it isn't possible to overload C functions, so using @extern "C"@ to declare functions is of limited use.
    1380 
    1381 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.
    1382 Ideally, structs should be manageable by default, since otherwise the default case becomes more verbose.
     878Furthermore, it is not possible to overload C functions, so using @extern "C"@ to declare functions is of limited use.
     879
     880It would be possible to regain some control by adding an attribute to structures 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.
     881Ideally, structures should be manageable by default, since otherwise the default case becomes more verbose.
    1383882This means that in general, function signatures would have to be rewritten, and in a select few cases the signatures would not be rewritten.
    1384883\begin{cfacode}
    1385 __attribute__((manageable)) struct A { ... };   // can declare constructors
    1386 __attribute__((unmanageable)) struct B { ... }; // cannot declare constructors
    1387 struct C { ... };                               // can declare constructors
     884__attribute__((manageable)) struct A { ... };   // can declare ctors
     885__attribute__((unmanageable)) struct B { ... }; // cannot declare ctors
     886struct C { ... };                               // can declare ctors
    1388887
    1389888A f();  // rewritten void f(A *);
     
    1391890C h();  // rewritten void h(C *);
    1392891\end{cfacode}
    1393 An alternative is to instead make the attribute \emph{identifiable}, which states that objects of this type use the @this@ parameter as an identity.
    1394 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.
     892An alternative is to make the attribute \emph{identifiable}, which states that objects of this type use the @this@ parameter as an identity.
     893This strikes more closely to the visible 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.
    1395894Furthermore, no restrictions would need to be placed on whether objects can be constructed.
    1396895\begin{cfacode}
    1397 __attribute__((identifiable)) struct A { ... };  // can declare constructors
    1398 struct B { ... };                                // can declare constructors
     896__attribute__((identifiable)) struct A { ... };  // can declare ctors
     897struct B { ... };                                // can declare ctors
    1399898
    1400899A f();  // rewritten void f(A *);
     
    1402901\end{cfacode}
    1403902
    1404 Ultimately, this is the type of transformation that a real compiler would make when generating assembly code.
    1405 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.
    1406 As such, it has been decided that this issue is not currently a priority.
     903Ultimately, both of these are patchwork solutions.
     904Since a real compiler has full control over its calling conventions, it can seamlessly allow passing the return parameter without outwardly changing the signature of a routine.
     905As such, it has been decided that this issue is not currently a priority and will be fixed when a full \CFA compiler is implemented.
    1407906
    1408907\section{Implementation}
    1409908\subsection{Array Initialization}
    1410 Arrays are a special case in the C type system.
     909Arrays are a special case in the C type-system.
    1411910C 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.
    1412911Instead, \CFA defines the initialization and destruction of an array recursively.
     
    15201019
    15211020\subsection{Global Initialization}
    1522 In standard C, global variables can only be initialized to compile-time constant expressions.
    1523 This places strict limitations on the programmer's ability to control the default values of objects.
     1021In standard C, global variables can only be initialized to compile-time constant expressions, which places strict limitations on the programmer's ability to control the default values of objects.
    15241022In \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.
    15251023By default, objects within a translation unit are constructed in declaration order, and destructed in the reverse order.
    15261024The default order of construction of objects amongst translation units is unspecified.
    1527 % TODO: not yet implemented, but g++ provides attribute init_priority, which allows specifying the order of global construction on a per object basis
    1528 %   https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes
    1529 % 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
    1530 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.
    1531 
    1532 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
     1025It is, however, guaranteed that any global objects in the standard library are initialized prior to the initialization of any object in a user program.
     1026
     1027This 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[6.31.1]{GCCExtensions}.
    15331028A similar function is generated with the \emph{destructor} attribute, which handles all global destructor calls.
    15341029At 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.
    1535 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.
     1030This 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 tear-down routines.
    15361031
    15371032For example, given the following global declarations.
     
    15591054\end{cfacode}
    15601055
     1056%   https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes
     1057% 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
     1058GCC provides an attribute @init_priority@ in \CC, which allows specifying the relative priority for initialization of global objects on a per-object basis.
     1059A similar attribute can be implemented in \CFA by pulling marked objects into global constructor/destructor-attribute functions with the specified priority.
     1060For example,
     1061\begin{cfacode}
     1062struct A { ... };
     1063void ?{}(A *, int);
     1064void ^?{}(A *);
     1065__attribute__((init_priority(200))) A x = { 123 };
     1066\end{cfacode}
     1067would generate
     1068\begin{cfacode}
     1069A x;
     1070__attribute__((constructor(200))) __init_x() {
     1071  ?{}(&x, 123);  // construct x with priority 200
     1072}
     1073__attribute__((destructor(200))) __destroy_x() {
     1074  ?{}(&x);       // destruct x with priority 200
     1075}
     1076\end{cfacode}
     1077
    15611078\subsection{Static Local Variables}
    15621079In standard C, it is possible to mark variables that are local to a function with the @static@ storage class.
    1563 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??
    1564 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.
     1080Unlike 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.
     1081Much like global variables, @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.
    15651082
    15661083Yet again, this rule is too restrictive for a language with constructors and destructors.
    1567 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.
    1568 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.
     1084Since the initializer expression is not necessarily a compile-time constant and can depend on the current execution state of the function, \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.
     1085Since standard C does not allow access to a @static@ local variable before the first time control flow reaches the declaration, this change does not preclude any valid C code.
    15691086Local objects with @static@ storage class are only implicitly constructed and destructed once for the duration of the program.
    15701087The object is constructed when its declaration is reached for the first time.
     
    15731090Construction of @static@ local objects is implemented via an accompanying @static bool@ variable, which records whether the variable has already been constructed.
    15741091A conditional branch checks the value of the companion @bool@, and if the variable has not yet been constructed then the object is constructed.
    1575 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.
     1092The object's destructor is scheduled to be run when the program terminates using @atexit@ \footnote{When using the dynamic linker, it is possible to dynamically load and unload a shared library. Since glibc 2.2.3 \cite{atexit}, functions registered with @atexit@ within the shared library are called when unloading the shared library. As such, static local objects can be destructed using this mechanism even in shared libraries on Linux systems.}, and the companion @bool@'s value is set so that subsequent invocations of the function do not reconstruct the object.
    15761093Since the parameter to @atexit@ is a parameter-less function, some additional tweaking is required.
    15771094First, the @static@ variable must be hoisted up to global scope and uniquely renamed to prevent name clashes with other global objects.
    1578 Second, a function is built which calls the destructor for the newly hoisted variable.
     1095If necessary, a local structure may need to be hoisted, as well.
     1096Second, a function is built that calls the destructor for the newly hoisted variable.
    15791097Finally, the newly generated function is registered with @atexit@, instead of registering the destructor directly.
    15801098Since @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.
    1581 
    15821099Extending the previous example
    15831100\begin{cfacode}
     
    16301147\end{cfacode}
    16311148
    1632 \subsection{Constructor Expressions}
    1633 In \CFA, it is possible to use a constructor as an expression.
    1634 Like other operators, the function name @?{}@ matches its operator syntax.
    1635 For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result.
    1636 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.
    1637 A key example is the use of constructor expressions to initialize the result of a call to standard C routine @malloc@.
    1638 \begin{cfacode}
    1639 struct X { ... };
    1640 void ?{}(X *, double);
    1641 X * x = malloc(sizeof(X)){ 1.5 };
    1642 \end{cfacode}
    1643 In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@.
    1644 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.
    1645 \begin{cfacode}
    1646 X * x = malloc(sizeof(X));
    1647 x{ 1.5 };
    1648 \end{cfacode}
    1649 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.
    1650 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.
    1651 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.
    1652 The previous example generates the following code.
    1653 \begin{cfacode}
    1654 struct X *_tmp_ctor;
    1655 struct X *x = ?{}((_tmp_ctor=((_tmp_cp_ret0=
    1656   malloc(sizeof(struct X))), _tmp_cp_ret0))), 1.5), _tmp_ctor);
    1657 \end{cfacode}
    1658 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.
    1659 
    1660 It is also possible to use operator syntax with destructors.
    1661 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.
    1662 For example, \lstinline!^(&x){}! calls the destructor on the variable @x@.
     1149\subsection{Polymorphism}
     1150As mentioned in section \ref{sub:polymorphism}, \CFA currently has 3 type-classes that are used to designate polymorphic data types: @otype@, @dtype@, and @ftype@.
     1151In previous versions of \CFA, @otype@ was syntactic sugar for @dtype@ with known size/alignment information and an assignment function.
     1152That is,
     1153\begin{cfacode}
     1154forall(otype T)
     1155void f(T);
     1156\end{cfacode}
     1157was equivalent to
     1158\begin{cfacode}
     1159forall(dtype T | sized(T) | { T ?=?(T *, T); })
     1160void f(T);
     1161\end{cfacode}
     1162This allows easily specifying constraints that are common to all complete object-types very simply.
     1163
     1164Now that \CFA has constructors and destructors, more of a complete object's behaviour can be specified than was previously possible.
     1165As such, @otype@ has been augmented to include assertions for a default constructor, copy constructor, and destructor.
     1166That is, the previous example is now equivalent to
     1167\begin{cfacode}
     1168forall(dtype T | sized(T) |
     1169  { T ?=?(T *, T); void ?{}(T *); void ?{}(T *, T); void ^?{}(T *); })
     1170void f(T);
     1171\end{cfacode}
     1172These additions allow @f@'s body to create and destroy objects of type @T@, and pass objects of type @T@ as arguments to other functions, following the normal \CFA rules.
     1173A point of note here is that objects can be missing default constructors (and eventually other functions through deleted functions), so it is important for \CFA programmers to think carefully about the operations needed by their function, as to not over-constrain the acceptable parameter types and prevent potential reuse.
Note: See TracChangeset for help on using the changeset viewer.