Changeset f92aa32 for doc/rob_thesis/ctordtor.tex
- Timestamp:
- Apr 7, 2017, 6:25:23 PM (8 years ago)
- Branches:
- ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
- Children:
- 2ccb93c
- Parents:
- c51b5a3
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
doc/rob_thesis/ctordtor.tex
rc51b5a3 rf92aa32 3 3 %====================================================================== 4 4 5 % TODO : as an experiment, implement Andrei Alexandrescu's ScopeGuard http://www.drdobbs.com/cpp/generic-change-the-way-you-write-excepti/184403758?pgno=25 % 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 6 6 % doesn't seem possible to do this without allowing ttype on generic structs? 7 8 % If a Cforall constructor is in scope, C style initialization is9 % disabled by default.10 % * initialization rule: if any constructor is in scope for type T, try11 % to find a matching constructor for the call. If there are no12 % constructors in scope for type T, then attempt to fall back on13 % C-style initialization.14 % + if this rule was not in place, it would be easy to accidentally15 % use C-style initialization in certain cases, which could lead to16 % subtle errors [2]17 % - this means we need special syntax if we want to allow users to force18 % a C-style initialization (to give users more control)19 % - two different declarations in the same scope can be implicitly20 % initialized differently. That is, there may be two objects of type21 % T that are initialized differently because there is a constructor22 % definition between them. This is not technically specific to23 % constructors.24 25 % C-style initializers can be accessed with @= syntax26 % + provides a way to get around the requirement of using a constructor27 % (for advanced programmers only)28 % - can break invariants in the type => unsafe29 % * provides a way of asserting that a variable is an instance of a30 % C struct (i.e. a POD struct), and so will not be implicitly31 % destructed (this can be useful at times, maybe mitigates the need32 % for move semantics?) [3]33 % + can modernize a code base one step at a time34 35 % Cforall constructors can be used in expressions to initialize any36 % piece of memory.37 % + malloc() { ... } calls the appropriate constructor on the newly38 % allocated space; the argument is moved into the constructor call39 % without taking its address [4]40 % - with the above form, there is still no way to ensure that41 % dynamically allocated objects are constructed. To resolve this,42 % we might want a stronger "new" function which always calls the43 % constructor, although how we accomplish that is currently still44 % unresolved (compiler magic vs. better variadic functions?)45 % + This can be used as a placement syntax [5]46 % - can call the constructor on an object more than once, which could47 % cause resource leaks and reinitialize const fields (can try to48 % detect and prevent this in some cases)49 % * compiler always tries to implicitly insert a ctor/dtor pair for50 % non-@= objects.51 % * For POD objects, this will resolve to an autogenerated or52 % intrinsic function.53 % * Intrinsic functions are not automatically called. Autogenerated54 % are, because they may call a non-autogenerated function.55 % * destructors are automatically inserted at appropriate branches56 % (e.g. return, break, continue, goto) and at the end of the block57 % in which they are declared.58 % * For @= objects, the compiler never tries to interfere and insert59 % constructor and destructor calls for that object. Copy constructor60 % calls do not count, because the object is not the target of the copy61 % constructor.62 63 % A constructor is declared with the name ?{}64 % + combines the look of C initializers with the precedent of ?() being65 % the name for the function call operator66 % + it is possible to easily search for all constructors in a project67 % and immediately know that a function is a constructor by seeing the68 % name "?{}"69 70 % A destructor is declared with the name ^?{}71 % + name mirrors a constructor's name, with an extra symbol to72 % distinguish it73 % - the symbol '~' cannot be used due to parsing conflicts with the74 % unary '~' (bitwise negation) operator - this conflict exists because75 % we want to allow users to write ^x{}; to destruct x, rather than76 % ^?{}(&x);77 78 % The first argument of a constructor must be a pointer. The constructed79 % type is the base type of the pointer. E.g. void ?{}(T *) is a default80 % constructor for a T.81 % + can name the argument whatever you like, so not constrained by82 % language keyword "this" or "self", etc.83 % - have to explicitly qualify all object members to initialize them84 % (e.g. this->x = 0, rather than just x = 0)85 86 % Destructors can take arguments other than just the destructed pointer87 % * open research problem: not sure how useful this is88 89 % Pointer constructors90 % + can construct separately compiled objects (opaque types) [6]91 % + orthogonal design, follows directly from the definition of the first92 % argument of a constructor93 % - may require copy constructor or move constructor (or equivalent)94 % for correct implementation, which may not be obvious to everyone95 % + required feature for the prelude to specify as much behavior as possible96 % (similar to pointer assignment operators in this respect)97 98 % Designations can only be used for C-style initialization99 % * designation for constructors is equivalent to designation for any100 % general function call. Since a function prototype can be redeclared101 % many times, with arguments named differently each time (or not at102 % all!), this is considered to be an undesirable feature. We could103 % construct some set of rules to allow this behaviour, but it is104 % probably more trouble than it's worth, and no matter what we choose,105 % it is not likely to be obvious to most people.106 107 % Constructing an anonymous member [7]108 % + same as with calling any other function on an anonymous member109 % (implicit conversion by the compiler)110 % - may be some cases where this is ambiguous => clarify with a cast111 % (try to design APIs to avoid sharing function signatures between112 % composed types to avoid this)113 114 % Default Constructors and Destructors are called implicitly115 % + cannot forget to construct or destruct an object116 % - requires special syntax to specify that an object is not to be117 % constructed (@=)118 % * an object will not be implicitly constructed OR destructed if119 % explicitly initialized like a C object (@= syntax)120 % * an object will be destructed if there are no constructors in scope121 % (even though it is initialized like a C object) [8]122 123 % An object which changes from POD type to non POD type will not change124 % the semantics of a type containing it by composition125 % * That is, constructors will not be regenerated at the point where126 % an object changes from POD type to non POD type, because this could127 % cause a cascade of constructors being regenerated for many other128 % types. Further, there is precedence for this behaviour in other129 % facets of Cforall's design, such as how nested functions interact.130 % * This behaviour can be simplified in a language without declaration131 % before use, because a type can be classified as POD or non POD132 % (rather than potentially changing between the two at some point) at133 % at the global scope (which is likely the most common case)134 % * [9]135 136 % Changes to polymorphic type classes137 % * dtype and ftype remain the same138 % * forall(otype T) is currently essentially the same as139 % forall(dtype T | { @size(T); void ?=?(T *, T); }).140 % The big addition is that you can declare an object of type T, rather141 % than just a pointer to an object of type T since you know the size,142 % and you can assign into a T.143 % * this definition is changed to add default constructor and144 % destructor declarations, to remain consistent with what type meant145 % before the introduction of constructors and destructors.146 % * that is, forall(type T) is now essentially the same as147 % forall(dtype T | { @size(T); void ?=?(T *, T);148 % void ?{}(T *); void ^?{}(T *); })149 % + this is required to make generic types work correctly in150 % polymorphic functions151 % ? since declaring a constructor invalidates the autogenerated152 % routines, it is possible for a type to have constructors, but153 % not default constructors. That is, it might be the case that154 % you want to write a polymorphic function for a type which has155 % a size, but non-default constructors? Some options:156 % * declaring a constructor as a part of the assertions list for157 % a type declaration invalidates the default, so158 % forall(otype T | { void ?{}(T *, int); })159 % really means160 % forall(dtype T | { @size(T); void ?=?(T *, T);161 % void ?{}(T *, int); void ^?{}(T *); })162 % * force users to fully declare the assertions list like the163 % above in this case (this seems very undesirable)164 % * add another type class with the current desugaring of type165 % (just size and assignment)166 % * provide some way of subtracting from an existing assertions167 % list (this might be useful to have in general)168 169 % Implementation issues:170 % Changes to prelude/autogen or built in defaults?171 % * pointer ctors/dtors [prelude]172 % * other pointer type routines are declared in the prelude, and this173 % doesn't seem like it should be any different174 % * basic type ctors/dtors [prelude]175 % * other basic type routines are declared in the prelude, and this176 % doesn't seem like it should be any different177 % ? aggregate types [undecided, but leaning towards autogenerate]178 % * prelude179 % * routines specific to aggregate types cannot be predeclared in180 % the prelude because we don't know the name of every181 % aggregate type in the entire program182 % * autogenerate183 % + default assignment operator is already autogenerated for184 % aggregate types185 % * this seems to lead us in the direction of autogenerating,186 % because we may have a struct which contains other objects187 % that require construction [10]. If we choose not to188 % autogenerate in this case, then objects which are part of189 % other objects by composition will not be constructed unless190 % a constructor for the outer type is explicitly defined191 % * in this case, we would always autogenerate the appropriate192 % constructor(s) for an aggregate type, but just like with193 % basic types, pointer types, and enum types, the constructor194 % call can be elided when when it is not necessary.195 % + constructors will have to be explicitly autogenerated196 % in the case where they are required for a polymorphic function,197 % when no user defined constructor is in scope, which may make it198 % easiest to always autogenerate all appropriate constructors199 % - n+2 constructors would have to be generated for a POD type200 % * one constructor for each number of valid arguments [0, n],201 % plus the copy constructor202 % * this is taking a simplified approach: in C, it is possible203 % to omit the enclosing braces in a declaration, which would204 % lead to a combinatorial explosion of generated constructors.205 % In the interest of keeping things tractable, Cforall may be206 % incompatible with C in this case. [11]207 % * for non-POD types, only autogenerate the default and copy208 % constructors209 % * alternative: generate only the default constructor and210 % special case initialization for any other constructor when211 % only the autogenerated one exists212 % - this is not very sensible, as by the previous point, these213 % constructors may be needed for polymorphic functions214 % anyway.215 % - must somehow distinguish in resolver between autogenerated and216 % user defined constructors (autogenerated should never be chosen217 % when a user defined option exists [check first parameter], even218 % if full signature differs) (this may also have applications219 % to other autogenerated routines?)220 % - this scheme does not naturally support designation (i.e. general221 % functions calls do not support designation), thus these cases222 % will have to be treated specially in either case223 % * defaults224 % * i.e. hardcode a new set of rules for some "appropriate" default225 % behaviour for226 % + when resolving an initialization expression, explicitly check to227 % see if any constructors are in scope. If yes, attempt to resolve228 % to a constructor, and produce an error message if a match is not229 % found. If there are no constructors in scope, resolve to230 % initializing each field individually (C-style)231 % + does not attempt to autogenerate constructors for POD types,232 % which can be seen as a space optimization for the program233 % binary234 % - as stated previously, a polymorphic routine may require these235 % autogenerated constructors, so this doesn't seem like a big win,236 % because this leads to more complicated logic and tracking of237 % which constructors have already been generated238 % - even though a constructor is not explicitly declared or used239 % polymorphically, we might still need one for all uses of a240 % struct (e.g. in the case of composition).241 % * the biggest tradeoff in autogenerating vs. defaulting appears to242 % be in where and how the special code to check if constructors are243 % present is handled. It appears that there are more reasons to244 % autogenerate than not.245 246 % --- examples247 % [1] As an example of using constructors polymorphically, consider a248 % slight modification on the foldl example I put on the mailing list a249 % few months ago:250 251 % context iterable(type collection, type element, type iterator) {252 % void ?{}(iterator *, collection); // used to be makeIterator, but can253 % // idiomatically use constructor254 % int hasNext(iterator);255 % iterator ++?(iterator *);256 % lvalue element *?(iterator);257 % };258 259 260 % forall(type collection, type element, type result, type iterator261 % | iterable(collection, element, iterator))262 % result foldl(collection c, result acc,263 % result (*reduce)(result, element)) {264 % iterator it = { c };265 % while (hasNext(it)) {266 % acc = reduce(acc, *it);267 % ++it;268 % }269 % return acc;270 % }271 272 % Now foldl makes use of the knowledge that the iterator type has a273 % single argument constructor which takes the collection to iterate274 % over. This pattern allows polymorphic code to look more natural275 % (constructors are generally preferred to named initializer/creation276 % routines, e.g. "makeIterator")277 278 % [2] An example of some potentially dangerous code that we don't want279 % to let easily slip through the cracks - if this is really what you280 % want, then use @= syntax for the second declaration to quiet the281 % compiler.282 283 % struct A { int x, y, z; }284 % ?{}(A *, int);285 % ?{}(A *, int, int, int);286 287 % A a1 = { 1 }; // uses ?{}(A *, int);288 % A a2 = { 2, 3 }; // C-style initialization -> no invariants!289 % A a3 = { 4, 5, 6 }; // uses ?{}(A *, int, int, int);290 291 % [3] Since @= syntax creates a C object (essentially a POD, as far as292 % the compiler is concerned), the object will not be destructed293 % implicitly when it leaves scope, nor will it be copy constructed when294 % it is returned. In this case, a memcpy should be equivalent to a move.295 296 % // Box.h297 % struct Box;298 % void ?{}(Box **, int};299 % void ^?{}(Box **);300 % Box * make_fortytwo();301 302 % // Box.cfa303 % Box * make_fortytwo() {304 % Box *b @= {};305 % (&b){ 42 }; // construct explicitly306 % return b; // no destruction, essentially a move?307 % }308 309 % [4] Cforall's typesafe malloc can be composed with constructor310 % expressions. It is possible for a user to define their own functions311 % similar to malloc and achieve the same effects (e.g. Aaron's example312 % of an arena allocator)313 314 % // CFA malloc315 % forall(type T)316 % T * malloc() { return (T *)malloc(sizeof(T)); }317 318 % struct A { int x, y, z; };319 % void ?{}(A *, int);320 321 % int foo(){322 % ...323 % // desugars to:324 % // A * a = ?{}(malloc(), 123);325 % A * a = malloc() { 123 };326 % ...327 % }328 329 % [5] Aaron's example of combining function calls with constructor330 % syntax to perform an operation similar to C++'s std::vector::emplace331 % (i.e. to construct a new element in place, without the need to332 % copy)333 334 % forall(type T)335 % struct vector {336 % T * elem;337 % int len;338 % ...339 % };340 341 % ...342 % forall(type T)343 % T * vector_new(vector(T) * v) {344 % // reallocate if needed345 % return &v->elem[len++];346 % }347 348 % int main() {349 % vector(int) * v = ...350 % vector_new(v){ 42 }; // add element to the end of vector351 % }352 353 % [6] Pointer Constructors. It could be useful to use the existing354 % constructor syntax even more uniformly for ADTs. With this, ADTs can355 % be initialized in the same manor as any other object in a polymorphic356 % function.357 358 % // vector.h359 % forall(type T) struct vector;360 % forall(type T) void ?{}(vector(T) **);361 % // adds an element to the end362 % forall(type T) vector(T) * ?+?(vector(T) *, T);363 364 % // vector.cfa365 % // don't want to expose the implementation to the user and/or don't366 % // want to recompile the entire program if the struct definition367 % // changes368 369 % forall(type T) struct vector {370 % T * elem;371 % int len;372 % int capacity;373 % };374 375 % forall(type T) void resize(vector(T) ** v) { ... }376 377 % forall(type T) void ?{}(vector(T) ** v) {378 % vector(T) * vect = *v = malloc();379 % vect->capacity = 10;380 % vect->len = 0;381 % vect->elem = malloc(vect->capacity);382 % }383 384 % forall(type T) vector(T) * ?+?(vector(T) *v, T elem) {385 % if (v->len == v->capacity) resize(&v);386 % v->elem[v->len++] = elem;387 % }388 389 % // main.cfa390 % #include "adt.h"391 % forall(type T | { T ?+?(T, int); }392 % T sumRange(int lower, int upper) {393 % T x; // default construct394 % for (int i = lower; i <= upper; i++) {395 % x = x + i;396 % }397 % return x;398 % }399 400 % int main() {401 % vector(int) * numbers = sumRange(1, 10);402 % // numbers is now a vector containing [1..10]403 404 % int sum = sumRange(1, 10);405 % // sum is now an int containing the value 55406 % }407 408 % [7] The current proposal is to use the plan 9 model of inheritance.409 % Under this model, all of the members of an unnamed struct instance410 % become members of the containing struct. In addition, an object411 % can be passed as an argument to a function expecting one of its412 % base structs.413 414 % struct Point {415 % double x;416 % double y;417 % };418 419 % struct ColoredPoint {420 % Point; // anonymous member (no identifier)421 % // => a ColoredPoint has an x and y of type double422 % int color;423 % };424 425 % ColoredPoint cp = ...;426 % cp.x = 10.3; // x from Point is accessed directly427 % cp.color = 0x33aaff; // color is accessed normally428 % foo(cp); // cp can be used directly as a Point429 430 % void ?{}(Point *p, double x, double y) {431 % p->x = x;432 % p->y = y;433 % }434 435 % void ?{}(ColoredPoint *cp, double x, double y, int color) {436 % (&cp){ x, y }; // unambiguous, no ?{}(ColoredPoint*,double,double)437 % cp->color = color;438 % }439 440 % struct Size {441 % double width;442 % double height;443 % };444 445 % void ?{}(Size *s, double w, double h) {446 % p->width = w;447 % p->height = h;448 % }449 450 % struct Foo {451 % Point;452 % Size;453 % }454 455 % ?{}(Foo &f, double x, double y, double w, double h) {456 % // (&F,x,y) is ambiguous => is it ?{}(Point*,double,double) or457 % // ?{}(Size*,double,double)? Solve with a cast:458 % ((Point*)&F){ x, y };459 % ((Size*)&F){ w, h };460 % }461 462 % [8] Destructors will be called on objects that were not constructed.463 464 % struct A { ... };465 % ^?{}(A *);466 % {467 % A x;468 % A y @= {};469 % } // x is destructed, even though it wasn't constructed470 % // y is not destructed, because it is explicitly a C object471 472 473 % [9] A type's constructor is generated at declaration time using474 % current information about an object's members. This is analogous to475 % the treatment of other operators. For example, an object's assignment476 % operator will not change to call the override of a member's assignment477 % operator unless the object's assignment is also explicitly overridden.478 % This problem can potentially be treated differently in Do, since each479 % compilation unit is passed over at least twice (once to gather480 % symbol information, once to generate code - this is necessary to481 % achieve the "No declarations" goal)482 483 % struct A { ... };484 % struct B { A x; };485 % ...486 % void ?{}(A *); // from this point on, A objects will be constructed487 % B b1; // b1 and b1.x are both NOT constructed, because B488 % // objects are not constructed489 % void ?{}(B *); // from this point on, B objects will be constructed490 % B b2; // b2 and b2.x are both constructed491 492 % struct C { A x; };493 % // implicit definition of ?{}(C*), because C is not a POD type since494 % // it contains a non-POD type by composition495 % C c; // c and c.x are both constructed496 497 % [10] Requiring construction by composition498 499 % struct A {500 % ...501 % };502 503 % // declared ctor disables default c-style initialization of504 % // A objects; A is no longer a POD type505 % void ?{}(A *);506 507 % struct B {508 % A x;509 % };510 511 % // B objects can not be C-style initialized, because A objects512 % // must be constructed => B objects are transitively not POD types513 % B b; // b.x must be constructed, but B is not constructible514 % // => must autogenerate ?{}(B *) after struct B definition,515 % // which calls ?{}(&b.x)516 517 % [11] Explosion in the number of generated constructors, due to strange518 % C semantics.519 520 % struct A { int x, y; };521 % struct B { A u, v, w; };522 523 % A a = { 0, 0 };524 525 % // in C, you are allowed to do this526 % B b1 = { 1, 2, 3, 4, 5, 6 };527 % B b2 = { 1, 2, 3 };528 % B b3 = { a, a, a };529 % B b4 = { a, 5, 4, a };530 % B b5 = { 1, 2, a, 3 };531 532 % // we want to disallow b1, b2, b4, and b5 in Cforall.533 % // In particular, we will autogenerate these constructors:534 % void ?{}(A *); // default/0 parameters535 % void ?{}(A *, int); // 1 parameter536 % void ?{}(A *, int, int); // 2 parameters537 % void ?{}(A *, const A *); // copy constructor538 539 % void ?{}(B *); // default/0 parameters540 % void ?{}(B *, A); // 1 parameter541 % void ?{}(B *, A, A); // 2 parameters542 % void ?{}(B *, A, A, A); // 3 parameters543 % void ?{}(B *, const B *); // copy constructor544 545 % // we will not generate constructors for every valid combination546 % // of members in C. For example, we will not generate547 % void ?{}(B *, int, int, int, int, int, int); // b1 would need this548 % void ?{}(B *, int, int, int); // b2 would need this549 % void ?{}(B *, A, int, int, A); // b4 would need this550 % void ?{}(B *, int, int, A, int); // b5 would need this551 % // and so on552 7 553 8 Since \CFA is a true systems language, it does not provide a garbage collector. … … 557 12 558 13 This chapter details the design of constructors and destructors in \CFA, along with their current implementation in the translator. 559 Generated code samples have been edited to provide comments for clarity and to save on space.14 Generated code samples have been edited for clarity and brevity. 560 15 561 16 \section{Design Criteria} … … 579 34 Use of uninitialized variables yields undefined behaviour, which is a common source of errors in C programs. 580 35 581 Declaration initialization is insufficient, because it permits uninitialized variables to exist and because it does not allow for the insertion of arbitrary code before a variable is live. 36 Initialization of a declaration is strictly optional, permitting uninitialized variables to exist. 37 Furthermore, declaration initialization is limited to expressions, so there is no way to insert arbitrary code before a variable is live, without delaying the declaration. 582 38 Many C compilers give good warnings for uninitialized variables most of the time, but they cannot in all cases. 583 39 \begin{cfacode} … … 592 48 Other languages are able to give errors in the case of uninitialized variable use, but due to backwards compatibility concerns, this is not the case in \CFA. 593 49 594 In C, constructors and destructors are often mimicked by providing routines that create and tear down objects, where the teardown function is typically only necessary if the type modifies the execution environment.50 In 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. 595 51 \begin{cfacode} 596 52 struct array_int { … … 618 74 Furthermore, even with this idiom it is easy to make mistakes, such as forgetting to destroy an object or destroying it multiple times. 619 75 620 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.76 A 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. 621 77 This goal is achieved through a guarantee that a constructor is called implicitly after every object is allocated from a type with associated constructors, as part of an object's definition. 622 78 Since a constructor is called on every object of a managed type, it is impossible to forget to initialize such objects, as long as all constructors perform some sensible form of initialization. … … 658 114 In other words, a default constructor is a constructor that takes a single argument: the @this@ parameter. 659 115 660 In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}! .116 In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}! and it take only one argument. 661 117 A destructor for the @Array@ type can be defined as such. 662 118 \begin{cfacode} … … 701 157 702 158 It is possible to define a constructor that takes any combination of parameters to provide additional initialization options. 703 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.159 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 elements of the array to a given @fill@ value. 704 160 \begin{cfacode} 705 161 void ?{}(Array * arr, int capacity, int fill) { … … 812 268 One of these three syntactic forms should appeal to either C or \CC programmers using \CFA. 813 269 270 \subsection{Constructor Expressions} 271 In \CFA, it is possible to use a constructor as an expression. 272 Like other operators, the function name @?{}@ matches its operator syntax. 273 For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result. 274 A key example for this capability is the use of constructor expressions to initialize the result of a call to standard C routine @malloc@. 275 \begin{cfacode} 276 struct X { ... }; 277 void ?{}(X *, double); 278 X * x = malloc(sizeof(X)){ 1.5 }; 279 \end{cfacode} 280 In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@. 281 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. 282 \begin{cfacode} 283 X * x = malloc(sizeof(X)); 284 x{ 1.5 }; 285 \end{cfacode} 286 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. 287 This 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. 288 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. 289 The previous example generates the following code. 290 \begin{cfacode} 291 struct X *_tmp_ctor; 292 struct X *x = ?{}( // construct result of malloc 293 _tmp_ctor=malloc(sizeof(struct X)), // store result of malloc 294 1.5 295 ), _tmp_ctor; // produce constructed result of malloc 296 \end{cfacode} 297 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. 298 299 It is also possible to use operator syntax with destructors. 300 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. 301 For example, \lstinline!^(&x){}! calls the destructor on the variable @x@. 302 814 303 \subsection{Function Generation} 815 In \CFA, every type is defined to have the core set of four functions described previously.304 In \CFA, every type is defined to have the core set of four special functions described previously. 816 305 Having these functions exist for every type greatly simplifies the semantics of the language, since most operations can simply be defined directly in terms of function calls. 817 306 In addition to simplifying the definition of the language, it also simplifies the analysis that the translator must perform. … … 826 315 827 316 The generated functions for enumerations are the simplest. 828 Since 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.317 Since 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. 829 318 For example, given the enumeration 830 319 \begin{cfacode} … … 839 328 } 840 329 void ?{}(enum Colour *_dst, enum Colour _src){ 841 (*_dst)=_src; // bitwise copy330 *_dst=_src; // bitwise copy 842 331 } 843 332 void ^?{}(enum Colour *_dst){ … … 845 334 } 846 335 enum Colour ?=?(enum Colour *_dst, enum Colour _src){ 847 return (*_dst)=_src; // bitwise copy336 return *_dst=_src; // bitwise copy 848 337 } 849 338 \end{cfacode} … … 903 392 For copy constructor and assignment operations, a bitwise @memcpy@ is applied. 904 393 In standard C, a union can also be initialized using a value of the same type as its first member, and so a corresponding field constructor is generated to perform a bitwise @memcpy@ of the object. 905 An alter antive 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.394 An 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. 906 395 This approach ultimately feels subtle and unsafe. 907 396 Another option is to, like \CC, disallow unions from containing members that are themselves managed types. … … 1000 489 Instead, @a2->x@ is initialized to @0@ as if it were a C object, because of the explicit initializer. 1001 490 1002 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.491 In addition to freedom, \ateq provides a simple path to migrating legacy C code to \CFA, in that objects can be moved from C-style initialization to \CFA gradually and individually. 1003 492 It is worth noting that the use of unmanaged objects can be tricky to get right, since there is no guarantee that the proper invariants are established on an unmanaged object. 1004 493 It is recommended that most objects be managed by sensible constructors and destructors, except where absolutely necessary. … … 1026 515 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. 1027 516 If an explicit call is present, then that call is taken in preference to any implicitly generated call. 1028 A 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 subobject initialization and destruction is always performed based on the declaration order.517 A 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. 1029 518 \begin{cfacode} 1030 519 struct A { … … 1045 534 } 1046 535 \end{cfacode} 1047 Finally, it is illegal for a sub object to be explicitly constructed for the first time after it is used for the first time.536 Finally, it is illegal for a sub-object to be explicitly constructed for the first time after it is used for the first time. 1048 537 If the translator cannot be reasonably sure that an object is constructed prior to its first use, but is constructed afterward, an error is emitted. 1049 More specifically, the translator searches the body of a constructor to ensure that every sub object is initialized.538 More specifically, the translator searches the body of a constructor to ensure that every sub-object is initialized. 1050 539 \begin{cfacode} 1051 540 void ?{}(A * a, double x) { … … 1054 543 } 1055 544 \end{cfacode} 1056 However, if the translator sees a sub object 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).545 However, 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). 1057 546 \begin{cfacode} 1058 547 void ?{}(A * a) { … … 1070 559 } // z, y, w implicitly destructed, in this order 1071 560 \end{cfacode} 1072 If at any point, the @this@ parameter is passed directly as the target of another constructor, then it is assumed that constructor handles the initialization of all of the object's members and no implicit constructor calls are added. % TODO: this is basically always wrong. if anything, I should check that such a constructor does not initialize any members, otherwise it'll always initialize the member twice (once locally, once by the called constructor). This might be okay in some situations, but it deserves a warning at the very least.561 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. 1073 562 To override this rule, \ateq can be used to force the translator to trust the programmer's discretion. 1074 563 This form of \ateq is not yet implemented. … … 1102 591 }; 1103 592 \end{cfacode} 1104 In C, nesting initializers means that the programmer intends to initialize sub objects with the nested initializers.593 In C, nesting initializers means that the programmer intends to initialize sub-objects with the nested initializers. 1105 594 The reason for this omission is to both simplify the mental model for using constructors, and to make initialization simpler for the expression resolver. 1106 595 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. … … 1125 614 } 1126 615 \end{cfacode} 1127 % TODO: in CFA if the array dimension is empty, no object constructors are added -- need to fix this.1128 616 The body of @A@ has been omitted, since only the constructor interfaces are important. 1129 617 … … 1153 641 if (i == 2) return; // destruct x, y 1154 642 } // destruct y 1155 } 643 } // destruct x 1156 644 \end{cfacode} 1157 645 … … 1169 657 Since a destructor call is automatically inserted at the end of the block, nothing special needs to happen to destruct @x@ in the case where control reaches the end of the loop. 1170 658 In the case where @i@ is @2@, the continue statement runs the loop update expression and attempts to begin the next iteration of the loop. 1171 Since continue is a C statement, which does not understand destructors, a destructor call is added just before the continue statementto ensure that @x@ is destructed.659 Since 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. 1172 660 When @i@ is @3@, the break statement moves control to just past the end of the loop. 1173 Like the previous case,a destructor call for @x@ is inserted just before the break statement.1174 1175 \CFA also supports label led break and continue statements, which allow more precise manipulation of control flow.1176 Label led break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure.661 Unlike the previous case, the destructor for @x@ cannot be reused, so a destructor call for @x@ is inserted just before the break statement. 662 663 \CFA also supports labeled break and continue statements, which allow more precise manipulation of control flow. 664 Labeled break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure. 1177 665 \begin{cfacode}[emph={L1,L2}, emphstyle=\color{red}] 1178 666 L1: for (int i = 0; i < 10; i++) { … … 1189 677 \end{cfacode} 1190 678 The statement @continue L1@ begins the next iteration of the outer for-loop. 1191 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@. 1192 % TODO: "why not do this all the time? fix or justify" 1193 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. 679 Since 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@. 680 Break, 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. 1194 681 1195 682 Finally, an example which demonstrates goto. … … 1238 725 } 1239 726 \end{cfacode} 1240 Labelled break and continue are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely goverened by these rules.727 All break and continue statements are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely governed by these rules. 1241 728 1242 729 The next example demonstrates the error case. … … 1255 742 1256 743 \subsection{Implicit Copy Construction} 744 \label{s:implicit_copy_construction} 1257 745 When a function is called, the arguments supplied to the call are subject to implicit copy construction (and destruction of the generated temporary), and the return value is subject to destruction. 1258 746 When a value is returned from a function, the copy constructor is called to pass the value back to the call site. 1259 Exempt from these rules are intrinsic and built in functions.747 Exempt from these rules are intrinsic and built-in functions. 1260 748 It should be noted that unmanaged objects are subject to copy constructor calls when passed as arguments to a function or when returned from a function, since they are not the \emph{target} of the copy constructor call. 1261 749 That is, since the parameter is not marked as an unmanaged object using \ateq, it will be copy constructed if it is returned by value or passed as an argument to another function, so to guarantee consistent behaviour, unmanaged objects must be copy constructed when passed as arguments. … … 1318 806 It should be noted that reference types will allow specifying that a value does not need to be copied, however reference types do not provide a means of preventing implicit copy construction from uses of the reference, so the problem is still present when passing or returning the reference by value. 1319 807 1320 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.1321 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.808 A 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. 809 In 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. 1322 810 This approach works out most of the time, because typically destructors need to only access the fields of the object and recursively destroy. 1323 811 It is currently the case that constructors and destructors that use the @this@ pointer as a unique identifier to store data externally do not work correctly for return value objects. 1324 Thus, it is not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program.812 Thus, it is currently not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program. 1325 813 \begin{cfacode} 1326 814 A * external_data[32]; … … 1350 838 \end{cfacode} 1351 839 In the above example, a global array of pointers is used to keep track of all of the allocated @A@ objects. 1352 Due to copying on return, the current object being destructed does not exist in the array if an @A@ object is ever returned by value from a function .840 Due to copying on return, the current object being destructed does not exist in the array if an @A@ object is ever returned by value from a function, such as in @makeA@. 1353 841 1354 842 This problem could be solved in the translator by changing the function signatures so that the return value is moved into the parameter list. … … 1399 887 \end{cfacode} 1400 888 An alternative is to instead make the attribute \emph{identifiable}, which states that objects of this type use the @this@ parameter as an identity. 1401 This strikes more closely to the visib ile 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.889 This 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. 1402 890 Furthermore, no restrictions would need to be placed on whether objects can be constructed. 1403 891 \begin{cfacode} … … 1409 897 \end{cfacode} 1410 898 1411 Ultimately, this is the type of transformation that a real compiler would make when generating assembly code.1412 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.1413 As such, it has been decided that this issue is not currently a priority .899 Ultimately, both of these are patchwork solutions. 900 Since 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. 901 As such, it has been decided that this issue is not currently a priority and will be fixed when a full \CFA compiler is implemented. 1414 902 1415 903 \section{Implementation} … … 1534 1022 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. 1535 1023 1536 This feature is implemented in the \CFA translator by grouping every global constructor call into a function with the GCC attribute \emph{constructor}, which performs most of the heavy lifting . % TODO: CITE: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes1024 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[6.31.1]{GCCExtensions}. 1537 1025 A similar function is generated with the \emph{destructor} attribute, which handles all global destructor calls. 1538 1026 At the time of writing, initialization routines in the library are specified with priority \emph{101}, which is the highest priority level that GCC allows, whereas initialization routines in the user's code are implicitly given the default priority level, which ensures they have a lower priority than any code with a specified priority level. 1539 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 tear down routines.1027 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 tear-down routines. 1540 1028 1541 1029 For example, given the following global declarations. … … 1565 1053 % https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes 1566 1054 % 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 1567 GCC provides an attribute @init_priority@, which specifiesallows specifying the relative priority for initialization of global objects on a per-object basis in \CC.1055 GCC provides an attribute @init_priority@, which allows specifying the relative priority for initialization of global objects on a per-object basis in \CC. 1568 1056 A similar attribute can be implemented in \CFA by pulling marked objects into global constructor/destructor-attribute functions with the specified priority. 1569 1057 For example, … … 1587 1075 \subsection{Static Local Variables} 1588 1076 In standard C, it is possible to mark variables that are local to a function with the @static@ storage class. 1589 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??1077 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. 1590 1078 Much like global variables, in C @static@ variables can only be initialized to a \emph{compile-time constant value} so that a compiler is able to create storage for the variable and initialize it at compile-time. 1591 1079 … … 1599 1087 Construction of @static@ local objects is implemented via an accompanying @static bool@ variable, which records whether the variable has already been constructed. 1600 1088 A conditional branch checks the value of the companion @bool@, and if the variable has not yet been constructed then the object is constructed. 1601 The object's destructor is scheduled to be run when the program terminates using @atexit@ , and the companion @bool@'s value is set so that subsequent invocations of the function do not reconstruct the object.1089 The 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. 1602 1090 Since the parameter to @atexit@ is a parameter-less function, some additional tweaking is required. 1603 1091 First, the @static@ variable must be hoisted up to global scope and uniquely renamed to prevent name clashes with other global objects. … … 1605 1093 Finally, the newly generated function is registered with @atexit@, instead of registering the destructor directly. 1606 1094 Since @atexit@ calls functions in the reverse order in which they are registered, @static@ local variables are guaranteed to be destructed in the reverse order that they are constructed, which may differ between multiple executions of the same program. 1607 1608 1095 Extending the previous example 1609 1096 \begin{cfacode} … … 1656 1143 \end{cfacode} 1657 1144 1658 % TODO: move this section forward?? maybe just after constructor syntax? would need to remove _tmp_cp_ret0, since copy constructors are not discussed yet, but this might not be a big issue. 1659 \subsection{Constructor Expressions} 1660 In \CFA, it is possible to use a constructor as an expression. 1661 Like other operators, the function name @?{}@ matches its operator syntax. 1662 For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result. 1663 A key example for this capability is the use of constructor expressions to initialize the result of a call to standard C routine @malloc@. 1664 \begin{cfacode} 1665 struct X { ... }; 1666 void ?{}(X *, double); 1667 X * x = malloc(sizeof(X)){ 1.5 }; 1668 \end{cfacode} 1669 In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@. 1670 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. 1671 \begin{cfacode} 1672 X * x = malloc(sizeof(X)); 1673 x{ 1.5 }; 1674 \end{cfacode} 1675 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. 1676 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. 1677 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. 1678 The previous example generates the following code. 1679 \begin{cfacode} 1680 struct X *_tmp_ctor; 1681 struct X *x = ?{}((_tmp_ctor=((_tmp_cp_ret0= 1682 malloc(sizeof(struct X))), _tmp_cp_ret0))), 1.5), _tmp_ctor); 1683 \end{cfacode} 1684 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. 1685 1686 It is also possible to use operator syntax with destructors. 1687 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. 1688 For example, \lstinline!^(&x){}! calls the destructor on the variable @x@. 1145 \subsection{Polymorphism} 1146 As mentioned in section \ref{sub:polymorphism}, \CFA currently has 3 type-classes that are used to designate polymorphic data types: @otype@, @dtype@, and @ftype@. 1147 In previous versions of \CFA, @otype@ was syntactic sugar for @dtype@ with known size/alignment information and an assignment function. 1148 That is, 1149 \begin{cfacode} 1150 forall(otype T) 1151 void f(T); 1152 \end{cfacode} 1153 was equivalent to 1154 \begin{cfacode} 1155 forall(dtype T | sized(T) | { T ?=?(T *, T); }) 1156 void f(T); 1157 \end{cfacode} 1158 This allows easily specifying constraints that are common to all complete object types very simply. 1159 1160 Now that \CFA has constructors and destructors, more of a complete object's behaviour can be specified by than was previously possible. 1161 As such, @otype@ has been augmented to include assertions for a default constructor, copy constructor, and destructor. 1162 That is, the previous example is now equivalent to 1163 \begin{cfacode} 1164 forall(dtype T | sized(T) | { T ?=?(T *, T); void ?{}(T *); void ?{}(T *, T); void ^?{}(T *); }) 1165 void f(T); 1166 \end{cfacode} 1167 This allows @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. 1168 A 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.
Note: See TracChangeset
for help on using the changeset viewer.