1 | %====================================================================== |
---|
2 | \chapter{Constructors and Destructors} |
---|
3 | %====================================================================== |
---|
4 | |
---|
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 |
---|
8 | % doesn't seem possible to do this without allowing ttype on generic structs? |
---|
9 | |
---|
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 | % Move semantics |
---|
139 | % * <ongoing discussion about this. this will be filled in |
---|
140 | % once we come to a consensus> |
---|
141 | |
---|
142 | % Changes to polymorphic type classes |
---|
143 | % * dtype and ftype remain the same |
---|
144 | % * forall(otype T) is currently essentially the same as |
---|
145 | % forall(dtype T | { @size(T); void ?=?(T *, T); }). |
---|
146 | % The big addition is that you can declare an object of type T, rather |
---|
147 | % than just a pointer to an object of type T since you know the size, |
---|
148 | % and you can assign into a T. |
---|
149 | % * this definition is changed to add default constructor and |
---|
150 | % destructor declarations, to remain consistent with what type meant |
---|
151 | % before the introduction of constructors and destructors. |
---|
152 | % * that is, forall(type T) is now essentially the same as |
---|
153 | % forall(dtype T | { @size(T); void ?=?(T *, T); |
---|
154 | % void ?{}(T *); void ^?{}(T *); }) |
---|
155 | % + this is required to make generic types work correctly in |
---|
156 | % polymorphic functions |
---|
157 | % ? since declaring a constructor invalidates the autogenerated |
---|
158 | % routines, it is possible for a type to have constructors, but |
---|
159 | % not default constructors. That is, it might be the case that |
---|
160 | % you want to write a polymorphic function for a type which has |
---|
161 | % a size, but non-default constructors? Some options: |
---|
162 | % * declaring a constructor as a part of the assertions list for |
---|
163 | % a type declaration invalidates the default, so |
---|
164 | % forall(otype T | { void ?{}(T *, int); }) |
---|
165 | % really means |
---|
166 | % forall(dtype T | { @size(T); void ?=?(T *, T); |
---|
167 | % void ?{}(T *, int); void ^?{}(T *); }) |
---|
168 | % * force users to fully declare the assertions list like the |
---|
169 | % above in this case (this seems very undesirable) |
---|
170 | % * add another type class with the current desugaring of type |
---|
171 | % (just size and assignment) |
---|
172 | % * provide some way of subtracting from an existing assertions |
---|
173 | % list (this might be useful to have in general) |
---|
174 | |
---|
175 | % Implementation issues: |
---|
176 | % Changes to prelude/autogen or built in defaults? |
---|
177 | % * pointer ctors/dtors [prelude] |
---|
178 | % * other pointer type routines are declared in the prelude, and this |
---|
179 | % doesn't seem like it should be any different |
---|
180 | % * basic type ctors/dtors [prelude] |
---|
181 | % * other basic type routines are declared in the prelude, and this |
---|
182 | % doesn't seem like it should be any different |
---|
183 | % ? aggregate types [undecided, but leaning towards autogenerate] |
---|
184 | % * prelude |
---|
185 | % * routines specific to aggregate types cannot be predeclared in |
---|
186 | % the prelude because we don't know the name of every |
---|
187 | % aggregate type in the entire program |
---|
188 | % * autogenerate |
---|
189 | % + default assignment operator is already autogenerated for |
---|
190 | % aggregate types |
---|
191 | % * this seems to lead us in the direction of autogenerating, |
---|
192 | % because we may have a struct which contains other objects |
---|
193 | % that require construction [10]. If we choose not to |
---|
194 | % autogenerate in this case, then objects which are part of |
---|
195 | % other objects by composition will not be constructed unless |
---|
196 | % a constructor for the outer type is explicitly defined |
---|
197 | % * in this case, we would always autogenerate the appropriate |
---|
198 | % constructor(s) for an aggregate type, but just like with |
---|
199 | % basic types, pointer types, and enum types, the constructor |
---|
200 | % call can be elided when when it is not necessary. |
---|
201 | % + constructors will have to be explicitly autogenerated |
---|
202 | % in the case where they are required for a polymorphic function, |
---|
203 | % when no user defined constructor is in scope, which may make it |
---|
204 | % easiest to always autogenerate all appropriate constructors |
---|
205 | % - n+2 constructors would have to be generated for a POD type |
---|
206 | % * one constructor for each number of valid arguments [0, n], |
---|
207 | % plus the copy constructor |
---|
208 | % * this is taking a simplified approach: in C, it is possible |
---|
209 | % to omit the enclosing braces in a declaration, which would |
---|
210 | % lead to a combinatorial explosion of generated constructors. |
---|
211 | % In the interest of keeping things tractable, Cforall may be |
---|
212 | % incompatible with C in this case. [11] |
---|
213 | % * for non-POD types, only autogenerate the default and copy |
---|
214 | % constructors |
---|
215 | % * alternative: generate only the default constructor and |
---|
216 | % special case initialization for any other constructor when |
---|
217 | % only the autogenerated one exists |
---|
218 | % - this is not very sensible, as by the previous point, these |
---|
219 | % constructors may be needed for polymorphic functions |
---|
220 | % anyway. |
---|
221 | % - must somehow distinguish in resolver between autogenerated and |
---|
222 | % user defined constructors (autogenerated should never be chosen |
---|
223 | % when a user defined option exists [check first parameter], even |
---|
224 | % if full signature differs) (this may also have applications |
---|
225 | % to other autogenerated routines?) |
---|
226 | % - this scheme does not naturally support designation (i.e. general |
---|
227 | % functions calls do not support designation), thus these cases |
---|
228 | % will have to be treated specially in either case |
---|
229 | % * defaults |
---|
230 | % * i.e. hardcode a new set of rules for some "appropriate" default |
---|
231 | % behaviour for |
---|
232 | % + when resolving an initialization expression, explicitly check to |
---|
233 | % see if any constructors are in scope. If yes, attempt to resolve |
---|
234 | % to a constructor, and produce an error message if a match is not |
---|
235 | % found. If there are no constructors in scope, resolve to |
---|
236 | % initializing each field individually (C-style) |
---|
237 | % + does not attempt to autogenerate constructors for POD types, |
---|
238 | % which can be seen as a space optimization for the program |
---|
239 | % binary |
---|
240 | % - as stated previously, a polymorphic routine may require these |
---|
241 | % autogenerated constructors, so this doesn't seem like a big win, |
---|
242 | % because this leads to more complicated logic and tracking of |
---|
243 | % which constructors have already been generated |
---|
244 | % - even though a constructor is not explicitly declared or used |
---|
245 | % polymorphically, we might still need one for all uses of a |
---|
246 | % struct (e.g. in the case of composition). |
---|
247 | % * the biggest tradeoff in autogenerating vs. defaulting appears to |
---|
248 | % be in where and how the special code to check if constructors are |
---|
249 | % present is handled. It appears that there are more reasons to |
---|
250 | % autogenerate than not. |
---|
251 | |
---|
252 | % --- examples |
---|
253 | % [1] As an example of using constructors polymorphically, consider a |
---|
254 | % slight modification on the foldl example I put on the mailing list a |
---|
255 | % few months ago: |
---|
256 | |
---|
257 | % context iterable(type collection, type element, type iterator) { |
---|
258 | % void ?{}(iterator *, collection); // used to be makeIterator, but can |
---|
259 | % // idiomatically use constructor |
---|
260 | % int hasNext(iterator); |
---|
261 | % iterator ++?(iterator *); |
---|
262 | % lvalue element *?(iterator); |
---|
263 | % }; |
---|
264 | |
---|
265 | |
---|
266 | % forall(type collection, type element, type result, type iterator |
---|
267 | % | iterable(collection, element, iterator)) |
---|
268 | % result foldl(collection c, result acc, |
---|
269 | % result (*reduce)(result, element)) { |
---|
270 | % iterator it = { c }; |
---|
271 | % while (hasNext(it)) { |
---|
272 | % acc = reduce(acc, *it); |
---|
273 | % ++it; |
---|
274 | % } |
---|
275 | % return acc; |
---|
276 | % } |
---|
277 | |
---|
278 | % Now foldl makes use of the knowledge that the iterator type has a |
---|
279 | % single argument constructor which takes the collection to iterate |
---|
280 | % over. This pattern allows polymorphic code to look more natural |
---|
281 | % (constructors are generally preferred to named initializer/creation |
---|
282 | % routines, e.g. "makeIterator") |
---|
283 | |
---|
284 | % [2] An example of some potentially dangerous code that we don't want |
---|
285 | % to let easily slip through the cracks - if this is really what you |
---|
286 | % want, then use @= syntax for the second declaration to quiet the |
---|
287 | % compiler. |
---|
288 | |
---|
289 | % struct A { int x, y, z; } |
---|
290 | % ?{}(A *, int); |
---|
291 | % ?{}(A *, int, int, int); |
---|
292 | |
---|
293 | % A a1 = { 1 }; // uses ?{}(A *, int); |
---|
294 | % A a2 = { 2, 3 }; // C-style initialization -> no invariants! |
---|
295 | % A a3 = { 4, 5, 6 }; // uses ?{}(A *, int, int, int); |
---|
296 | |
---|
297 | % [3] Since @= syntax creates a C object (essentially a POD, as far as |
---|
298 | % the compiler is concerned), the object will not be destructed |
---|
299 | % implicitly when it leaves scope, nor will it be copy constructed when |
---|
300 | % it is returned. In this case, a memcpy should be equivalent to a move. |
---|
301 | |
---|
302 | % // Box.h |
---|
303 | % struct Box; |
---|
304 | % void ?{}(Box **, int}; |
---|
305 | % void ^?{}(Box **); |
---|
306 | % Box * make_fortytwo(); |
---|
307 | |
---|
308 | % // Box.cfa |
---|
309 | % Box * make_fortytwo() { |
---|
310 | % Box *b @= {}; |
---|
311 | % (&b){ 42 }; // construct explicitly |
---|
312 | % return b; // no destruction, essentially a move? |
---|
313 | % } |
---|
314 | |
---|
315 | % [4] Cforall's typesafe malloc can be composed with constructor |
---|
316 | % expressions. It is possible for a user to define their own functions |
---|
317 | % similar to malloc and achieve the same effects (e.g. Aaron's example |
---|
318 | % of an arena allocator) |
---|
319 | |
---|
320 | % // CFA malloc |
---|
321 | % forall(type T) |
---|
322 | % T * malloc() { return (T *)malloc(sizeof(T)); } |
---|
323 | |
---|
324 | % struct A { int x, y, z; }; |
---|
325 | % void ?{}(A *, int); |
---|
326 | |
---|
327 | % int foo(){ |
---|
328 | % ... |
---|
329 | % // desugars to: |
---|
330 | % // A * a = ?{}(malloc(), 123); |
---|
331 | % A * a = malloc() { 123 }; |
---|
332 | % ... |
---|
333 | % } |
---|
334 | |
---|
335 | % [5] Aaron's example of combining function calls with constructor |
---|
336 | % syntax to perform an operation similar to C++'s std::vector::emplace |
---|
337 | % (i.e. to construct a new element in place, without the need to |
---|
338 | % copy) |
---|
339 | |
---|
340 | % forall(type T) |
---|
341 | % struct vector { |
---|
342 | % T * elem; |
---|
343 | % int len; |
---|
344 | % ... |
---|
345 | % }; |
---|
346 | |
---|
347 | % ... |
---|
348 | % forall(type T) |
---|
349 | % T * vector_new(vector(T) * v) { |
---|
350 | % // reallocate if needed |
---|
351 | % return &v->elem[len++]; |
---|
352 | % } |
---|
353 | |
---|
354 | % int main() { |
---|
355 | % vector(int) * v = ... |
---|
356 | % vector_new(v){ 42 }; // add element to the end of vector |
---|
357 | % } |
---|
358 | |
---|
359 | % [6] Pointer Constructors. It could be useful to use the existing |
---|
360 | % constructor syntax even more uniformly for ADTs. With this, ADTs can |
---|
361 | % be initialized in the same manor as any other object in a polymorphic |
---|
362 | % function. |
---|
363 | |
---|
364 | % // vector.h |
---|
365 | % forall(type T) struct vector; |
---|
366 | % forall(type T) void ?{}(vector(T) **); |
---|
367 | % // adds an element to the end |
---|
368 | % forall(type T) vector(T) * ?+?(vector(T) *, T); |
---|
369 | |
---|
370 | % // vector.cfa |
---|
371 | % // don't want to expose the implementation to the user and/or don't |
---|
372 | % // want to recompile the entire program if the struct definition |
---|
373 | % // changes |
---|
374 | |
---|
375 | % forall(type T) struct vector { |
---|
376 | % T * elem; |
---|
377 | % int len; |
---|
378 | % int capacity; |
---|
379 | % }; |
---|
380 | |
---|
381 | % forall(type T) void resize(vector(T) ** v) { ... } |
---|
382 | |
---|
383 | % forall(type T) void ?{}(vector(T) ** v) { |
---|
384 | % vector(T) * vect = *v = malloc(); |
---|
385 | % vect->capacity = 10; |
---|
386 | % vect->len = 0; |
---|
387 | % vect->elem = malloc(vect->capacity); |
---|
388 | % } |
---|
389 | |
---|
390 | % forall(type T) vector(T) * ?+?(vector(T) *v, T elem) { |
---|
391 | % if (v->len == v->capacity) resize(&v); |
---|
392 | % v->elem[v->len++] = elem; |
---|
393 | % } |
---|
394 | |
---|
395 | % // main.cfa |
---|
396 | % #include "adt.h" |
---|
397 | % forall(type T | { T ?+?(T, int); } |
---|
398 | % T sumRange(int lower, int upper) { |
---|
399 | % T x; // default construct |
---|
400 | % for (int i = lower; i <= upper; i++) { |
---|
401 | % x = x + i; |
---|
402 | % } |
---|
403 | % return x; |
---|
404 | % } |
---|
405 | |
---|
406 | % int main() { |
---|
407 | % vector(int) * numbers = sumRange(1, 10); |
---|
408 | % // numbers is now a vector containing [1..10] |
---|
409 | |
---|
410 | % int sum = sumRange(1, 10); |
---|
411 | % // sum is now an int containing the value 55 |
---|
412 | % } |
---|
413 | |
---|
414 | % [7] The current proposal is to use the plan 9 model of inheritance. |
---|
415 | % Under this model, all of the members of an unnamed struct instance |
---|
416 | % become members of the containing struct. In addition, an object |
---|
417 | % can be passed as an argument to a function expecting one of its |
---|
418 | % base structs. |
---|
419 | |
---|
420 | % struct Point { |
---|
421 | % double x; |
---|
422 | % double y; |
---|
423 | % }; |
---|
424 | |
---|
425 | % struct ColoredPoint { |
---|
426 | % Point; // anonymous member (no identifier) |
---|
427 | % // => a ColoredPoint has an x and y of type double |
---|
428 | % int color; |
---|
429 | % }; |
---|
430 | |
---|
431 | % ColoredPoint cp = ...; |
---|
432 | % cp.x = 10.3; // x from Point is accessed directly |
---|
433 | % cp.color = 0x33aaff; // color is accessed normally |
---|
434 | % foo(cp); // cp can be used directly as a Point |
---|
435 | |
---|
436 | % void ?{}(Point *p, double x, double y) { |
---|
437 | % p->x = x; |
---|
438 | % p->y = y; |
---|
439 | % } |
---|
440 | |
---|
441 | % void ?{}(ColoredPoint *cp, double x, double y, int color) { |
---|
442 | % (&cp){ x, y }; // unambiguous, no ?{}(ColoredPoint*,double,double) |
---|
443 | % cp->color = color; |
---|
444 | % } |
---|
445 | |
---|
446 | % struct Size { |
---|
447 | % double width; |
---|
448 | % double height; |
---|
449 | % }; |
---|
450 | |
---|
451 | % void ?{}(Size *s, double w, double h) { |
---|
452 | % p->width = w; |
---|
453 | % p->height = h; |
---|
454 | % } |
---|
455 | |
---|
456 | % struct Foo { |
---|
457 | % Point; |
---|
458 | % Size; |
---|
459 | % } |
---|
460 | |
---|
461 | % ?{}(Foo &f, double x, double y, double w, double h) { |
---|
462 | % // (&F,x,y) is ambiguous => is it ?{}(Point*,double,double) or |
---|
463 | % // ?{}(Size*,double,double)? Solve with a cast: |
---|
464 | % ((Point*)&F){ x, y }; |
---|
465 | % ((Size*)&F){ w, h }; |
---|
466 | % } |
---|
467 | |
---|
468 | % [8] Destructors will be called on objects that were not constructed. |
---|
469 | |
---|
470 | % struct A { ... }; |
---|
471 | % ^?{}(A *); |
---|
472 | % { |
---|
473 | % A x; |
---|
474 | % A y @= {}; |
---|
475 | % } // x is destructed, even though it wasn't constructed |
---|
476 | % // y is not destructed, because it is explicitly a C object |
---|
477 | |
---|
478 | |
---|
479 | % [9] A type's constructor is generated at declaration time using |
---|
480 | % current information about an object's members. This is analogous to |
---|
481 | % the treatment of other operators. For example, an object's assignment |
---|
482 | % operator will not change to call the override of a member's assignment |
---|
483 | % operator unless the object's assignment is also explicitly overridden. |
---|
484 | % This problem can potentially be treated differently in Do, since each |
---|
485 | % compilation unit is passed over at least twice (once to gather |
---|
486 | % symbol information, once to generate code - this is necessary to |
---|
487 | % achieve the "No declarations" goal) |
---|
488 | |
---|
489 | % struct A { ... }; |
---|
490 | % struct B { A x; }; |
---|
491 | % ... |
---|
492 | % void ?{}(A *); // from this point on, A objects will be constructed |
---|
493 | % B b1; // b1 and b1.x are both NOT constructed, because B |
---|
494 | % // objects are not constructed |
---|
495 | % void ?{}(B *); // from this point on, B objects will be constructed |
---|
496 | % B b2; // b2 and b2.x are both constructed |
---|
497 | |
---|
498 | % struct C { A x; }; |
---|
499 | % // implicit definition of ?{}(C*), because C is not a POD type since |
---|
500 | % // it contains a non-POD type by composition |
---|
501 | % C c; // c and c.x are both constructed |
---|
502 | |
---|
503 | % [10] Requiring construction by composition |
---|
504 | |
---|
505 | % struct A { |
---|
506 | % ... |
---|
507 | % }; |
---|
508 | |
---|
509 | % // declared ctor disables default c-style initialization of |
---|
510 | % // A objects; A is no longer a POD type |
---|
511 | % void ?{}(A *); |
---|
512 | |
---|
513 | % struct B { |
---|
514 | % A x; |
---|
515 | % }; |
---|
516 | |
---|
517 | % // B objects can not be C-style initialized, because A objects |
---|
518 | % // must be constructed => B objects are transitively not POD types |
---|
519 | % B b; // b.x must be constructed, but B is not constructible |
---|
520 | % // => must autogenerate ?{}(B *) after struct B definition, |
---|
521 | % // which calls ?{}(&b.x) |
---|
522 | |
---|
523 | % [11] Explosion in the number of generated constructors, due to strange |
---|
524 | % C semantics. |
---|
525 | |
---|
526 | % struct A { int x, y; }; |
---|
527 | % struct B { A u, v, w; }; |
---|
528 | |
---|
529 | % A a = { 0, 0 }; |
---|
530 | |
---|
531 | % // in C, you are allowed to do this |
---|
532 | % B b1 = { 1, 2, 3, 4, 5, 6 }; |
---|
533 | % B b2 = { 1, 2, 3 }; |
---|
534 | % B b3 = { a, a, a }; |
---|
535 | % B b4 = { a, 5, 4, a }; |
---|
536 | % B b5 = { 1, 2, a, 3 }; |
---|
537 | |
---|
538 | % // we want to disallow b1, b2, b4, and b5 in Cforall. |
---|
539 | % // In particular, we will autogenerate these constructors: |
---|
540 | % void ?{}(A *); // default/0 parameters |
---|
541 | % void ?{}(A *, int); // 1 parameter |
---|
542 | % void ?{}(A *, int, int); // 2 parameters |
---|
543 | % void ?{}(A *, const A *); // copy constructor |
---|
544 | |
---|
545 | % void ?{}(B *); // default/0 parameters |
---|
546 | % void ?{}(B *, A); // 1 parameter |
---|
547 | % void ?{}(B *, A, A); // 2 parameters |
---|
548 | % void ?{}(B *, A, A, A); // 3 parameters |
---|
549 | % void ?{}(B *, const B *); // copy constructor |
---|
550 | |
---|
551 | % // we will not generate constructors for every valid combination |
---|
552 | % // of members in C. For example, we will not generate |
---|
553 | % void ?{}(B *, int, int, int, int, int, int); // b1 would need this |
---|
554 | % void ?{}(B *, int, int, int); // b2 would need this |
---|
555 | % void ?{}(B *, A, int, int, A); // b4 would need this |
---|
556 | % void ?{}(B *, int, int, A, int); // b5 would need this |
---|
557 | % // and so on |
---|
558 | |
---|
559 | |
---|
560 | |
---|
561 | % TODO: talk somewhere about compound literals? |
---|
562 | |
---|
563 | Since \CFA is a true systems language, it does not provide a garbage collector. |
---|
564 | As well, \CFA is not an object-oriented programming language, i.e. structures cannot have routine members. |
---|
565 | Nevertheless, one important goal is to reduce programming complexity and increase safety. |
---|
566 | To that end, \CFA provides support for implicit pre/post-execution of routines for objects, via constructors and destructors. |
---|
567 | |
---|
568 | % TODO: this is old. remove or refactor |
---|
569 | % Manual resource management is difficult. |
---|
570 | % Part of the difficulty results from not having any guarantees about the current state of an object. |
---|
571 | % 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. |
---|
572 | |
---|
573 | % 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. |
---|
574 | % 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. |
---|
575 | % Constructors and destructors can help to simplify resource management when used in a disciplined way. |
---|
576 | % In particular, when all resources are acquired in a constructor, and all resources are released in a destructor, no resource leaks are possible. |
---|
577 | % This pattern is a popular idiom in several languages, such as \CC, known as RAII (Resource Acquisition Is Initialization). |
---|
578 | |
---|
579 | This chapter details the design of constructors and destructors in \CFA, along with their current implementation in the translator. |
---|
580 | Generated code samples have been edited to provide comments for clarity and to save on space. |
---|
581 | |
---|
582 | \section{Design Criteria} |
---|
583 | \label{s:Design} |
---|
584 | In designing constructors and destructors for \CFA, the primary goals were ease of use and maintaining backwards compatibility. |
---|
585 | |
---|
586 | In C, when a variable is defined, its value is initially undefined unless it is explicitly initialized or allocated in the static area. |
---|
587 | \begin{cfacode} |
---|
588 | int main() { |
---|
589 | int x; // uninitialized |
---|
590 | int y = 5; // initialized to 5 |
---|
591 | x = y; // assigned 5 |
---|
592 | static int z; // initialized to 0 |
---|
593 | } |
---|
594 | \end{cfacode} |
---|
595 | In the example above, @x@ is defined and left uninitialized, while @y@ is defined and initialized to 5. |
---|
596 | Next, @x@ is assigned the value of @y@. |
---|
597 | In the last line, @z@ is implicitly initialized to 0 since it is marked @static@. |
---|
598 | The key difference between assignment and initialization being that assignment occurs on a live object (i.e. an object that contains data). |
---|
599 | It is important to note that this means @x@ could have been used uninitialized prior to being assigned, while @y@ could not be used uninitialized. |
---|
600 | Use of uninitialized variables yields undefined behaviour, which is a common source of errors in C programs. % TODO: *citation* |
---|
601 | |
---|
602 | 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. |
---|
603 | Many C compilers give good warnings most of the time, but they cannot in all cases. |
---|
604 | \begin{cfacode} |
---|
605 | int f(int *); // never reads the parameter, only writes |
---|
606 | int g(int *); // reads the parameter - expects an initialized variable |
---|
607 | |
---|
608 | int x, y; |
---|
609 | f(&x); // okay - only writes to x |
---|
610 | g(&y); // will use y uninitialized |
---|
611 | \end{cfacode} |
---|
612 | 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. |
---|
613 | |
---|
614 | 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. |
---|
615 | \begin{cfacode} |
---|
616 | struct array_int { |
---|
617 | int * x; |
---|
618 | }; |
---|
619 | struct array_int create_array(int sz) { |
---|
620 | return (struct array_int) { malloc(sizeof(int)*sz) }; |
---|
621 | } |
---|
622 | void destroy_rh(struct resource_holder * rh) { |
---|
623 | free(rh->x); |
---|
624 | } |
---|
625 | \end{cfacode} |
---|
626 | This idiom does not provide any guarantees unless the structure is opaque, which then requires that all objects are heap allocated. |
---|
627 | \begin{cfacode} |
---|
628 | struct opqaue_array_int; |
---|
629 | struct opqaue_array_int * create_opqaue_array(int sz); |
---|
630 | void destroy_opaque_array(opaque_array_int *); |
---|
631 | int opaque_get(opaque_array_int *); // subscript |
---|
632 | |
---|
633 | opaque_array_int * x = create_opaque_array(10); |
---|
634 | int x2 = opaque_get(x, 2); |
---|
635 | \end{cfacode} |
---|
636 | This pattern is cumbersome to use since every access becomes a function call. |
---|
637 | While useful in some situations, this compromise is too restrictive. |
---|
638 | Furthermore, even with this idiom it is easy to make mistakes, such as forgetting to destroy an object or destroying it multiple times. |
---|
639 | |
---|
640 | 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. |
---|
641 | 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. |
---|
642 | 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. |
---|
643 | |
---|
644 | In \CFA, a constructor is a function with the name @?{}@. |
---|
645 | Every constructor must have a return type of @void@ and at least one parameter, the first of which is colloquially referred to as the \emph{this} parameter, as in many object-oriented programming-languages (however, a programmer can give it an arbitrary name). |
---|
646 | The @this@ parameter must have a pointer type, whose base type is the type of object that the function constructs. |
---|
647 | There is precedence for enforcing the first parameter to be the @this@ parameter in other operators, such as the assignment operator, where in both cases, the left-hand side of the equals is the first parameter. |
---|
648 | There is currently a proposal to add reference types to \CFA. |
---|
649 | Once this proposal has been implemented, the @this@ parameter will become a reference type with the same restrictions. |
---|
650 | |
---|
651 | Consider the definition of a simple type encapsulating a dynamic array of @int@s. |
---|
652 | |
---|
653 | \begin{cfacode} |
---|
654 | struct Array { |
---|
655 | int * data; |
---|
656 | int len; |
---|
657 | } |
---|
658 | \end{cfacode} |
---|
659 | |
---|
660 | In C, if the user creates an @Array@ object, the fields @data@ and @len@ are uninitialized, unless an explicit initializer list is present. |
---|
661 | It is the user's responsibility to remember to initialize both of the fields to sensible values. |
---|
662 | In \CFA, the user can define a constructor to handle initialization of @Array@ objects. |
---|
663 | |
---|
664 | \begin{cfacode} |
---|
665 | void ?{}(Array * arr){ |
---|
666 | arr->len = 10; // default size |
---|
667 | arr->data = malloc(sizeof(int)*arr->len); |
---|
668 | for (int i = 0; i < arr->len; ++i) { |
---|
669 | arr->data[i] = 0; |
---|
670 | } |
---|
671 | } |
---|
672 | Array x; // allocates storage for Array and calls ?{}(&x) |
---|
673 | \end{cfacode} |
---|
674 | |
---|
675 | This constructor initializes @x@ so that its @length@ field has the value 10, and its @data@ field holds a pointer to a block of memory large enough to hold 10 @int@s, and sets the value of each element of the array to 0. |
---|
676 | This particular form of constructor is called the \emph{default constructor}, because it is called on an object defined without an initializer. |
---|
677 | In other words, a default constructor is a constructor that takes a single argument, the @this@ parameter. |
---|
678 | |
---|
679 | In \CFA, a destructor is a function much like a constructor, except that its name is \lstinline!^?{}!. |
---|
680 | A destructor for the @Array@ type can be defined as such. |
---|
681 | \begin{cfacode} |
---|
682 | void ^?{}(Array * arr) { |
---|
683 | free(arr->data); |
---|
684 | } |
---|
685 | \end{cfacode} |
---|
686 | 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. |
---|
687 | The exact guarantees made by \CFA with respect to the calling of destructors are discussed in section \ref{sub:implicit_dtor}. |
---|
688 | |
---|
689 | As discussed previously, the distinction between initialization and assignment is important. |
---|
690 | Consider the following example. |
---|
691 | \begin{cfacode}[numbers=left] |
---|
692 | Array x, y; |
---|
693 | Array z = x; // initialization |
---|
694 | y = x; // assignment |
---|
695 | \end{cfacode} |
---|
696 | By the previous definition of the default constructor for @Array@, @x@ and @y@ are initialized to valid arrays of length 10 after their respective definitions. |
---|
697 | On line 3, @z@ is initialized with the value of @x@, while on line @4@, @y@ is assigned the value of @x@. |
---|
698 | The key distinction between initialization and assignment is that a value to be initialized does not hold any meaningful values, whereas an object to be assigned might. |
---|
699 | In particular, these cases cannot be handled the same way because in the former case @z@ does not currently own an array, while @y@ does. |
---|
700 | |
---|
701 | \begin{cfacode}[emph={other}, emphstyle=\color{red}] |
---|
702 | void ?{}(Array * arr, Array other) { // copy constructor |
---|
703 | arr->len = other.len; // initialization |
---|
704 | arr->data = malloc(sizeof(int)*arr->len) |
---|
705 | for (int i = 0; i < arr->len; ++i) { |
---|
706 | arr->data[i] = other.data[i]; // copy from other object |
---|
707 | } |
---|
708 | } |
---|
709 | Array ?=?(Array * arr, Array other) { // assignment |
---|
710 | ^?{}(arr); // explicitly call destructor |
---|
711 | ?{}(arr, other); // explicitly call constructor |
---|
712 | return *arr; |
---|
713 | } |
---|
714 | \end{cfacode} |
---|
715 | The two functions above handle these cases. |
---|
716 | The first function is called a \emph{copy constructor}, because it constructs its argument by copying the values from another object of the same type. |
---|
717 | The second function is the standard copy-assignment operator. |
---|
718 | These four functions are special in that they control the state of most objects. |
---|
719 | |
---|
720 | It is possible to define a constructor that takes any combination of parameters to provide additional initialization options. |
---|
721 | 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. |
---|
722 | \begin{cfacode} |
---|
723 | void ?{}(Array * arr, int capacity, int fill) { |
---|
724 | arr->len = capacity; |
---|
725 | arr->data = malloc(sizeof(int)*arr->len); |
---|
726 | for (int i = 0; i < arr->len; ++i) { |
---|
727 | arr->data[i] = fill; |
---|
728 | } |
---|
729 | } |
---|
730 | \end{cfacode} |
---|
731 | In \CFA, constructors are called implicitly in initialization contexts. |
---|
732 | \begin{cfacode} |
---|
733 | Array x, y = { 20, 0xdeadbeef }, z = y; |
---|
734 | \end{cfacode} |
---|
735 | 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. |
---|
736 | 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. |
---|
737 | |
---|
738 | This example generates the following code |
---|
739 | \begin{cfacode} |
---|
740 | Array x; |
---|
741 | ?{}(&x); // implicit default construct |
---|
742 | Array y; |
---|
743 | ?{}(&y, 20, 0xdeadbeef); // explicit fill construct |
---|
744 | Array z; |
---|
745 | ?{}(&z, y); // copy construct |
---|
746 | ^?{}(&z); // implicit destruct |
---|
747 | ^?{}(&y); // implicit destruct |
---|
748 | ^?{}(&x); // implicit destruct |
---|
749 | \end{cfacode} |
---|
750 | Due to the way that constructor calls are interleaved, it is impossible for @y@ to be referenced before it is initialized, except in its own constructor. |
---|
751 | This loophole is minor and exists in \CC as well. |
---|
752 | Destructors are implicitly called in reverse declaration-order so that objects with dependencies are destructed before the objects they are dependent on. |
---|
753 | |
---|
754 | \subsection{Syntax} |
---|
755 | \label{sub:syntax} % TODO: finish this section |
---|
756 | There are several ways to construct an object in \CFA. |
---|
757 | As previously introduced, every variable is automatically constructed at its definition, which is the most natural way to construct an object. |
---|
758 | \begin{cfacode} |
---|
759 | struct A { ... }; |
---|
760 | void ?{}(A *); |
---|
761 | void ?{}(A *, A); |
---|
762 | void ?{}(A *, int, int); |
---|
763 | |
---|
764 | A a1; // default constructed |
---|
765 | A a2 = { 0, 0 }; // constructed with 2 ints |
---|
766 | A a3 = a1; // copy constructed |
---|
767 | // implicitly destruct a3, a2, a1, in that order |
---|
768 | \end{cfacode} |
---|
769 | Since constructors and destructors are just functions, the second way is to call the function directly. |
---|
770 | \begin{cfacode} |
---|
771 | struct A { int a; }; |
---|
772 | void ?{}(A *); |
---|
773 | void ?{}(A *, A); |
---|
774 | void ^?{}(A *); |
---|
775 | |
---|
776 | A x; // implicitly default constructed: ?{}(&x) |
---|
777 | A * y = malloc(); // copy construct: ?{}(&y, malloc()) |
---|
778 | |
---|
779 | ?{}(&x); // explicit construct x |
---|
780 | ?{}(y, x); // explit construct y from x |
---|
781 | ^?{}(&x); // explicit destroy x |
---|
782 | ^?{}(y); // explicit destroy y |
---|
783 | |
---|
784 | // implicit ^?{}(&y); |
---|
785 | // implicit ^?{}(&x); |
---|
786 | \end{cfacode} |
---|
787 | Calling a constructor or destructor directly is a flexible feature that allows complete control over the management of a piece of storage. |
---|
788 | In particular, constructors double as a placement syntax. |
---|
789 | \begin{cfacode} |
---|
790 | struct A { ... }; |
---|
791 | struct memory_pool { ... }; |
---|
792 | void ?{}(memory_pool *, size_t); |
---|
793 | |
---|
794 | memory_pool pool = { 1024 }; // create an arena of size 1024 |
---|
795 | |
---|
796 | A * a = allocate(&pool); // allocate from memory pool |
---|
797 | ?{}(a); // construct an A in place |
---|
798 | |
---|
799 | for (int i = 0; i < 10; i++) { |
---|
800 | // reuse storage rather than reallocating |
---|
801 | ^?{}(a); |
---|
802 | ?{}(a); |
---|
803 | // use a ... |
---|
804 | } |
---|
805 | ^?{}(a); |
---|
806 | deallocate(&pool, a); // return to memory pool |
---|
807 | \end{cfacode} |
---|
808 | Finally, constructors and destructors support \emph{operator syntax}. |
---|
809 | 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. |
---|
810 | \begin{cfacode} |
---|
811 | struct A { ... }; |
---|
812 | struct B { A a; }; |
---|
813 | |
---|
814 | A x, y, * z = &x; |
---|
815 | (&x){} // default construct |
---|
816 | (&x){ y } // copy construct |
---|
817 | (&x){ 1, 2, 3 } // construct with 3 arguments |
---|
818 | z{ y }; // copy construct x through a pointer |
---|
819 | ^(&x){} // destruct |
---|
820 | |
---|
821 | void ?{}(B * b) { |
---|
822 | (&b->a){ 11, 17, 13 }; // construct a member |
---|
823 | } |
---|
824 | \end{cfacode} |
---|
825 | Constructor operator syntax has relatively high precedence, requiring parentheses around an address-of expression. |
---|
826 | Destructor operator syntax is actually an statement, and requires parentheses for symmetry with constructor syntax. |
---|
827 | |
---|
828 | \subsection{Function Generation} |
---|
829 | In \CFA, every type is defined to have the core set of four functions described previously. |
---|
830 | 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. |
---|
831 | In addition to simplifying the definition of the language, it also simplifies the analysis that the translator must perform. |
---|
832 | If the translator can expect these functions to exist, then it can unconditionally attempt to resolve them. |
---|
833 | Moreover, the existence of a standard interface allows polymorphic code to interoperate with new types seamlessly. |
---|
834 | |
---|
835 | To mimic the behaviour of standard C, the default constructor and destructor for all of the basic types and for all pointer types are defined to do nothing, while the copy constructor and assignment operator perform a bitwise copy of the source parameter (as in \CC). |
---|
836 | |
---|
837 | There are several options for user-defined types: structures, unions, and enumerations. |
---|
838 | To aid in ease of use, the standard set of four functions is automatically generated for a user-defined type after its definition is completed. |
---|
839 | 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. |
---|
840 | |
---|
841 | The generated functions for enumerations are the simplest. |
---|
842 | 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. |
---|
843 | % TODO: examples for enums |
---|
844 | For example, given the enumeration |
---|
845 | \begin{cfacode} |
---|
846 | enum Colour { |
---|
847 | R, G, B |
---|
848 | }; |
---|
849 | \end{cfacode} |
---|
850 | The following functions are automatically generated. |
---|
851 | \begin{cfacode} |
---|
852 | void ?{}(enum Colour *_dst){ |
---|
853 | // default constructor does nothing |
---|
854 | } |
---|
855 | void ?{}(enum Colour *_dst, enum Colour _src){ |
---|
856 | (*_dst)=_src; // bitwise copy |
---|
857 | } |
---|
858 | void ^?{}(enum Colour *_dst){ |
---|
859 | // destructor does nothing |
---|
860 | } |
---|
861 | enum Colour ?=?(enum Colour *_dst, enum Colour _src){ |
---|
862 | return (*_dst)=_src; // bitwise copy |
---|
863 | } |
---|
864 | \end{cfacode} |
---|
865 | In the future, \CFA will introduce strongly-typed enumerations, like those in \CC. |
---|
866 | 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. |
---|
867 | Changes related to this feature only need to affect the expression resolution phase, where more strict rules will be applied to prevent implicit conversions from integral types to enumeration types, but should continue to permit conversions from enumeration types to @int@. |
---|
868 | 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. |
---|
869 | |
---|
870 | For structures, the situation is more complicated. |
---|
871 | 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$@. |
---|
872 | That is, a default constructor for @S@ default constructs the members of @S@, the copy constructor with copy construct them, and so on. |
---|
873 | For example given the struct definition |
---|
874 | \begin{cfacode} |
---|
875 | struct A { |
---|
876 | B b; |
---|
877 | C c; |
---|
878 | } |
---|
879 | \end{cfacode} |
---|
880 | The following functions are implicitly generated. |
---|
881 | \begin{cfacode} |
---|
882 | void ?{}(A * this) { |
---|
883 | ?{}(&this->b); // default construct each field |
---|
884 | ?{}(&this->c); |
---|
885 | } |
---|
886 | void ?{}(A * this, A other) { |
---|
887 | ?{}(&this->b, other.b); // copy construct each field |
---|
888 | ?{}(&this->c, other.c); |
---|
889 | } |
---|
890 | A ?=?(A * this, A other) { |
---|
891 | ?=?(&this->b, other.b); // assign each field |
---|
892 | ?=?(&this->c, other.c); |
---|
893 | } |
---|
894 | void ^?{}(A * this) { |
---|
895 | ^?{}(&this->c); // destruct each field |
---|
896 | ^?{}(&this->b); |
---|
897 | } |
---|
898 | \end{cfacode} |
---|
899 | 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. |
---|
900 | |
---|
901 | In addition to the standard set, a set of \emph{field constructors} is also generated for structures. |
---|
902 | The field constructors are constructors that consume a prefix of the struct's member list. |
---|
903 | That is, $N$ constructors are built of the form @void ?{}(S *, T$_{\text{M}_0}$)@, @void ?{}(S *, T$_{\text{M}_0}$, T$_{\text{M}_1}$)@, ..., @void ?{}(S *, T$_{\text{M}_0}$, T$_{\text{M}_1}$, ..., T$_{\text{M}_{N-1}}$)@, where members are copy constructed if they have a corresponding positional argument and are default constructed otherwise. |
---|
904 | 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 }@. |
---|
905 | Extending the previous example, the following constructors are implicitly generated for @A@. |
---|
906 | \begin{cfacode} |
---|
907 | void ?{}(A * this, B b) { |
---|
908 | ?{}(&this->b, b); |
---|
909 | ?{}(&this->c); |
---|
910 | } |
---|
911 | void ?{}(A * this, B b, C c) { |
---|
912 | ?{}(&this->b, b); |
---|
913 | ?{}(&this->c, c); |
---|
914 | } |
---|
915 | \end{cfacode} |
---|
916 | |
---|
917 | For unions, the default constructor and destructor do nothing, as it is not obvious which member if any should be constructed. |
---|
918 | For copy constructor and assignment operations, a bitwise @memcpy@ is applied. |
---|
919 | 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. |
---|
920 | 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. |
---|
921 | This approach ultimately feels subtle and unsafe. |
---|
922 | Another option is to, like \CC, disallow unions from containing members that are themselves managed types. |
---|
923 | This restriction is a reasonable approach from a safety standpoint, but is not very C-like. |
---|
924 | Since the primary purpose of a union is to provide low-level memory optimization, it is assumed that the user has a certain level of maturity. |
---|
925 | It is therefore the responsibility of the user to define the special functions explicitly if they are appropriate, since it is impossible to accurately predict the ways that a union is intended to be used at compile-time. |
---|
926 | |
---|
927 | For example, given the union |
---|
928 | \begin{cfacode} |
---|
929 | union X { |
---|
930 | Y y; |
---|
931 | Z z; |
---|
932 | }; |
---|
933 | \end{cfacode} |
---|
934 | The following functions are automatically generated. |
---|
935 | \begin{cfacode} |
---|
936 | void ?{}(union X *_dst){ // default constructor |
---|
937 | } |
---|
938 | void ?{}(union X *_dst, union X _src){ // copy constructor |
---|
939 | __builtin_memcpy(_dst, &_src, sizeof(union X )); |
---|
940 | } |
---|
941 | void ^?{}(union X *_dst){ // destructor |
---|
942 | } |
---|
943 | union X ?=?(union X *_dst, union X _src){ // assignment |
---|
944 | __builtin_memcpy(_dst, &_src, sizeof(union X)); |
---|
945 | return _src; |
---|
946 | } |
---|
947 | void ?{}(union X *_dst, struct Y src){ // construct first field |
---|
948 | __builtin_memcpy(_dst, &src, sizeof(struct Y)); |
---|
949 | } |
---|
950 | \end{cfacode} |
---|
951 | |
---|
952 | % 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 |
---|
953 | 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. |
---|
954 | This restriction could easily be added into \CFA once \emph{deleted} functions are added. |
---|
955 | |
---|
956 | \subsection{Using Constructors and Destructors} |
---|
957 | 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. |
---|
958 | For example, |
---|
959 | \begin{cfacode} |
---|
960 | struct S { int i; }; |
---|
961 | void ?{}(S *, int); |
---|
962 | void ?{}(S *, S); |
---|
963 | |
---|
964 | const S s = { 11 }; |
---|
965 | volatile S s2 = s; |
---|
966 | \end{cfacode} |
---|
967 | Generates the following code |
---|
968 | \begin{cfacode} |
---|
969 | const struct S s; |
---|
970 | ?{}((struct S *)&s, 11); |
---|
971 | volatile struct S s2; |
---|
972 | ?{}((struct S *)&s2, s); |
---|
973 | \end{cfacode} |
---|
974 | Here, @&s@ and @&s2@ are cast to unqualified pointer types. |
---|
975 | This mechanism allows the same constructors and destructors to be used for qualified objects as for unqualified objects. |
---|
976 | 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. |
---|
977 | |
---|
978 | Unlike \CC, \CFA provides an escape hatch that allows a user to decide at an object's definition whether it should be managed or not. |
---|
979 | An object initialized with \ateq is guaranteed to be initialized like a C object, and has no implicit destructor call. |
---|
980 | This feature provides all of the freedom that C programmers are used to having to optimize a program, while maintaining safety as a sensible default. |
---|
981 | \begin{cfacode} |
---|
982 | struct A { int * x; }; |
---|
983 | // RAII |
---|
984 | void ?{}(A * a) { a->x = malloc(sizeof(int)); } |
---|
985 | void ^?{}(A * a) { free(a->x); } |
---|
986 | |
---|
987 | A a1; // managed |
---|
988 | A a2 @= { 0 }; // unmanaged |
---|
989 | \end{cfacode} |
---|
990 | 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. |
---|
991 | Instead, @a2->x@ is initialized to @0@ as if it were a C object, due to the explicit initializer. |
---|
992 | Existing constructors are ignored when \ateq is used, so that any valid C initializer is able to initialize the object. |
---|
993 | |
---|
994 | 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. |
---|
995 | 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. |
---|
996 | It is recommended that most objects be managed by sensible constructors and destructors, except where absolutely necessary. |
---|
997 | |
---|
998 | 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. |
---|
999 | 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. |
---|
1000 | 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?? |
---|
1001 | \begin{cfacode} |
---|
1002 | struct S { int x, y; }; |
---|
1003 | |
---|
1004 | void f() { |
---|
1005 | S s0, s1 = { 0 }, s2 = { 0, 2 }, s3 = s2; // okay |
---|
1006 | { |
---|
1007 | void ?{}(S * s, int i) { s->x = i*2; } |
---|
1008 | S s4; // error |
---|
1009 | S s5 = { 3 }; // okay |
---|
1010 | S s6 = { 4, 5 }; // error |
---|
1011 | S s7 = s5; // okay |
---|
1012 | } |
---|
1013 | S s8, s9 = { 6 }, s10 = { 7, 8 }, s11 = s10; // okay |
---|
1014 | } |
---|
1015 | \end{cfacode} |
---|
1016 | In this example, the inner scope declares a constructor from @int@ to @S@, which hides the default constructor and field constructors until the end of the scope. |
---|
1017 | |
---|
1018 | 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. |
---|
1019 | If an explicit call is present, then that call is taken in preference to any implicitly generated call. |
---|
1020 | 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. |
---|
1021 | \begin{cfacode} |
---|
1022 | struct A { |
---|
1023 | B w, x, y, z; |
---|
1024 | }; |
---|
1025 | void ?{}(A * a, int i) { |
---|
1026 | (&a->x){ i }; |
---|
1027 | (&a->z){ a->y }; |
---|
1028 | } |
---|
1029 | \end{cfacode} |
---|
1030 | Generates the following |
---|
1031 | \begin{cfacode} |
---|
1032 | void ?{}(A * a, int i) { |
---|
1033 | (&a->w){}; // implicit default ctor |
---|
1034 | (&a->y){}; // implicit default ctor |
---|
1035 | (&a->x){ i }; |
---|
1036 | (&a->z){ a->y }; |
---|
1037 | } |
---|
1038 | \end{cfacode} |
---|
1039 | Finally, it is illegal for a subobject to be explicitly constructed for the first time after it is used for the first time. |
---|
1040 | 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. |
---|
1041 | More specifically, the translator searches the body of a constructor to ensure that every subobject is initialized. |
---|
1042 | \begin{cfacode} |
---|
1043 | void ?{}(A * a, double x) { |
---|
1044 | f(a->x); |
---|
1045 | (&a->x){ (int)x }; // error, used uninitialized on previous line |
---|
1046 | } |
---|
1047 | \end{cfacode} |
---|
1048 | 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). |
---|
1049 | \begin{cfacode} |
---|
1050 | void ?{}(A * a) { |
---|
1051 | // default constructs all members |
---|
1052 | f(a->x); |
---|
1053 | } |
---|
1054 | |
---|
1055 | void ?{}(A * a, A other) { |
---|
1056 | // copy constructs all members |
---|
1057 | f(a->y); |
---|
1058 | } |
---|
1059 | |
---|
1060 | void ^?{}(A * a) { |
---|
1061 | ^(&a->x){}; // explicit destructor call |
---|
1062 | } // z, y, w implicitly destructed, in this order |
---|
1063 | \end{cfacode} |
---|
1064 | 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). |
---|
1065 | To override this rule, \ateq can be used to force the translator to trust the programmer's discretion. |
---|
1066 | This form of \ateq is not yet implemented. |
---|
1067 | |
---|
1068 | Despite great effort, some forms of C syntax do not work well with constructors in \CFA. |
---|
1069 | In particular, constructor calls cannot contain designations (see \ref{sub:c_background}), since this is equivalent to allowing designations on the arguments to arbitrary function calls. |
---|
1070 | 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. |
---|
1071 | Furthermore, a function prototype can be repeated an arbitrary number of times, each time using different names. |
---|
1072 | \begin{cfacode} |
---|
1073 | // all legal forward declarations in C |
---|
1074 | void f(int, int, int); |
---|
1075 | void f(int a, int b, int c); |
---|
1076 | void f(int b, int c, int a); |
---|
1077 | void f(int c, int a, int b); |
---|
1078 | void f(int x, int y, int z); |
---|
1079 | |
---|
1080 | f(b:10, a:20, c:30); // which parameter is which? |
---|
1081 | \end{cfacode} |
---|
1082 | As a result, it was decided that any attempt to resolve designated function calls with C's function prototype rules would be brittle, and thus it is not sensible to allow designations in constructor calls. |
---|
1083 | % 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. |
---|
1084 | |
---|
1085 | 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. |
---|
1086 | For example, |
---|
1087 | \begin{cfacode} |
---|
1088 | struct A; |
---|
1089 | void ?{}(A *, int); |
---|
1090 | void ?{}(A *, A, A); |
---|
1091 | |
---|
1092 | A a1[3] = { { 3 }, { 4 }, { 5 } }; |
---|
1093 | A a2[2][2] = { |
---|
1094 | { { 9 }, { 10 } }, // a2[0] |
---|
1095 | { {14 }, { 15 } } // a2[1] |
---|
1096 | }; |
---|
1097 | A a3[4] = { |
---|
1098 | { { 11 }, { 12 } }, // error |
---|
1099 | { 80 }, { 90 }, { 100 } |
---|
1100 | } |
---|
1101 | \end{cfacode} |
---|
1102 | % TODO: in CFA if the array dimension is empty, no object constructors are added -- need to fix this. |
---|
1103 | The body of @A@ has been omitted, since only the constructor interfaces are important. |
---|
1104 | In C, having a greater nesting depth means that the programmer intends to initialize subobjects with the nested initializer. |
---|
1105 | 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 | 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. |
---|
1107 | 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)@. |
---|
1108 | 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. |
---|
1109 | It should be noted that unmanaged objects can still make use of designations and nested initializers in \CFA. |
---|
1110 | |
---|
1111 | \subsection{Implicit Destructors} |
---|
1112 | \label{sub:implicit_dtor} |
---|
1113 | Destructors are automatically called at the end of the block in which the object is declared. |
---|
1114 | 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. |
---|
1115 | The example below demonstrates a simple routine with multiple return statements. |
---|
1116 | \begin{cfacode} |
---|
1117 | struct A; |
---|
1118 | void ^?{}(A *); |
---|
1119 | |
---|
1120 | void f(int i) { |
---|
1121 | A x; // construct x |
---|
1122 | { |
---|
1123 | A y; // construct y |
---|
1124 | { |
---|
1125 | A z; // construct z |
---|
1126 | { |
---|
1127 | if (i == 0) return; // destruct x, y, z |
---|
1128 | } |
---|
1129 | if (i == 1) return; // destruct x, y, z |
---|
1130 | } // destruct z |
---|
1131 | if (i == 2) return; // destruct x, y |
---|
1132 | } // destruct y |
---|
1133 | } |
---|
1134 | \end{cfacode} |
---|
1135 | |
---|
1136 | %% having this feels excessive, but it's here if necessary |
---|
1137 | % This procedure generates the following code. |
---|
1138 | % \begin{cfacode} |
---|
1139 | % void f(int i){ |
---|
1140 | % struct A x; |
---|
1141 | % ?{}(&x); |
---|
1142 | % { |
---|
1143 | % struct A y; |
---|
1144 | % ?{}(&y); |
---|
1145 | % { |
---|
1146 | % struct A z; |
---|
1147 | % ?{}(&z); |
---|
1148 | % { |
---|
1149 | % if ((i==0)!=0) { |
---|
1150 | % ^?{}(&z); |
---|
1151 | % ^?{}(&y); |
---|
1152 | % ^?{}(&x); |
---|
1153 | % return; |
---|
1154 | % } |
---|
1155 | % } |
---|
1156 | % if (((i==1)!=0) { |
---|
1157 | % ^?{}(&z); |
---|
1158 | % ^?{}(&y); |
---|
1159 | % ^?{}(&x); |
---|
1160 | % return ; |
---|
1161 | % } |
---|
1162 | % ^?{}(&z); |
---|
1163 | % } |
---|
1164 | |
---|
1165 | % if ((i==2)!=0) { |
---|
1166 | % ^?{}(&y); |
---|
1167 | % ^?{}(&x); |
---|
1168 | % return; |
---|
1169 | % } |
---|
1170 | % ^?{}(&y); |
---|
1171 | % } |
---|
1172 | |
---|
1173 | % ^?{}(&x); |
---|
1174 | % } |
---|
1175 | % \end{cfacode} |
---|
1176 | |
---|
1177 | The next example illustrates the use of simple continue and break statements and the manner that they interact with implicit destructors. |
---|
1178 | \begin{cfacode} |
---|
1179 | for (int i = 0; i < 10; i++) { |
---|
1180 | A x; |
---|
1181 | if (i == 2) { |
---|
1182 | continue; // destruct x |
---|
1183 | } else if (i == 3) { |
---|
1184 | break; // destruct x |
---|
1185 | } |
---|
1186 | } // destruct x |
---|
1187 | \end{cfacode} |
---|
1188 | 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. |
---|
1189 | 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. |
---|
1190 | 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. |
---|
1191 | When @i@ is @3@, the break statement moves control to just past the end of the loop. |
---|
1192 | Like the previous case, a destructor call for @x@ is inserted just before the break statement. |
---|
1193 | |
---|
1194 | \CFA also supports labelled break and continue statements, which allow more precise manipulation of control flow. |
---|
1195 | Labelled break and continue allow the programmer to specify which control structure to target by using a label attached to a control structure. |
---|
1196 | \begin{cfacode}[emph={L1,L2}, emphstyle=\color{red}] |
---|
1197 | L1: for (int i = 0; i < 10; i++) { |
---|
1198 | A x; |
---|
1199 | L2: for (int j = 0; j < 10; j++) { |
---|
1200 | A y; |
---|
1201 | if (j == 0) { |
---|
1202 | continue; // destruct y |
---|
1203 | } else if (j == 1) { |
---|
1204 | break; // destruct y |
---|
1205 | } else if (i == 1) { |
---|
1206 | continue L1; // destruct y |
---|
1207 | } else if (i == 2) { |
---|
1208 | break L1; // destruct x,y |
---|
1209 | } |
---|
1210 | } // destruct y |
---|
1211 | } // destruct X |
---|
1212 | \end{cfacode} |
---|
1213 | The statement @continue L1@ begins the next iteration of the outer for-loop. |
---|
1214 | 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@. |
---|
1215 | 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. |
---|
1216 | |
---|
1217 | Finally, an example which demonstrates goto. |
---|
1218 | Since goto is a general mechanism for jumping to different locations in the program, a more comprehensive approach is required. |
---|
1219 | For each goto statement $G$ and each target label $L$, let $S_G$ be the set of all managed variables alive at $G$, and let $S_L$ be the set of all managed variables alive at $L$. |
---|
1220 | If at any $G$, $S_L \setminus S_G = \emptyset$, then the translator emits an error, because control flow branches from a point where the object is not yet live to a point where it is live, skipping the object's constructor. |
---|
1221 | Then, for every $G$, the destructors for each variable in the set $S_G \setminus S_L$ is inserted directly before $G$, which ensures each object that is currently live at $G$, but not at $L$, is destructed before control branches. |
---|
1222 | \begin{cfacode} |
---|
1223 | int i = 0; |
---|
1224 | { |
---|
1225 | L0: ; // S_L0 = { x } |
---|
1226 | A y; |
---|
1227 | L1: ; // S_L1 = { x } |
---|
1228 | A x; |
---|
1229 | L2: ; // S_L2 = { y, x } |
---|
1230 | if (i == 0) { |
---|
1231 | ++i; |
---|
1232 | goto L1; // S_G = { y, x } |
---|
1233 | // S_G-S_L1 = { x } => destruct x |
---|
1234 | } else if (i == 1) { |
---|
1235 | ++i; |
---|
1236 | goto L2; // S_G = { y, x } |
---|
1237 | // S_G-S_L2 = {} => destruct nothing |
---|
1238 | } else if (i == 2) { |
---|
1239 | ++i; |
---|
1240 | goto L3; // S_G = { y, x } |
---|
1241 | // S_G-S_L3 = {} |
---|
1242 | } else if (false) { |
---|
1243 | ++i; |
---|
1244 | A z; |
---|
1245 | goto L3; // S_G = { z, y, x } |
---|
1246 | // S_G-S_L3 = { z } => destruct z |
---|
1247 | } else { |
---|
1248 | ++i; |
---|
1249 | goto L4; // S_G = { y, x } |
---|
1250 | // S_G-S_L4 = { y, x } => destruct y, x |
---|
1251 | } |
---|
1252 | L3: ; // S_L3 = { y, x } |
---|
1253 | goto L2; // S_G = { y, x } |
---|
1254 | // S_G-S_L2 = {} |
---|
1255 | } |
---|
1256 | L4: ; // S_L4 = {} |
---|
1257 | if (i == 4) { |
---|
1258 | goto L0; // S_G = {} |
---|
1259 | // S_G-S_L0 = {} |
---|
1260 | } |
---|
1261 | \end{cfacode} |
---|
1262 | Labelled break and continue are implemented in \CFA in terms of goto statements, so the more constrained forms are precisely goverened by these rules. |
---|
1263 | |
---|
1264 | The next example demonstrates the error case. |
---|
1265 | \begin{cfacode} |
---|
1266 | { |
---|
1267 | goto L1; // S_G = {} |
---|
1268 | // S_L1-S_G = { y } => error |
---|
1269 | A y; |
---|
1270 | L1: ; // S_L1 = { y } |
---|
1271 | A x; |
---|
1272 | L2: ; // S_L2 = { y, x } |
---|
1273 | } |
---|
1274 | goto L2; // S_G = {} |
---|
1275 | // S_L2-S_G = { y, x } => error |
---|
1276 | \end{cfacode} |
---|
1277 | |
---|
1278 | \subsection{Implicit Copy Construction} |
---|
1279 | 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. |
---|
1280 | When a value is returned from a function, the copy constructor is called to pass the value back to the call site. |
---|
1281 | Exempt from these rules are intrinsic and builtin functions. |
---|
1282 | 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. |
---|
1283 | 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. |
---|
1284 | \begin{cfacode} |
---|
1285 | struct A; |
---|
1286 | void ?{}(A *); |
---|
1287 | void ?{}(A *, A); |
---|
1288 | void ^?{}(A *); |
---|
1289 | |
---|
1290 | A f(A x) { |
---|
1291 | return x; |
---|
1292 | } |
---|
1293 | |
---|
1294 | A y, z @= {}; |
---|
1295 | identity(y); |
---|
1296 | identity(z); |
---|
1297 | \end{cfacode} |
---|
1298 | Note that @z@ is copy constructed into a temporary variable to be passed as an argument, which is also destructed after the call. |
---|
1299 | 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. |
---|
1300 | |
---|
1301 | This generates the following |
---|
1302 | \begin{cfacode} |
---|
1303 | struct A f(struct A x){ |
---|
1304 | struct A _retval_f; |
---|
1305 | ?{}((&_retval_f), x); |
---|
1306 | return _retval_f; |
---|
1307 | } |
---|
1308 | |
---|
1309 | struct A y; |
---|
1310 | ?{}(&y); |
---|
1311 | struct A z = { 0 }; |
---|
1312 | |
---|
1313 | struct A _tmp_cp1; // argument 1 |
---|
1314 | struct A _tmp_cp_ret0; // return value |
---|
1315 | _tmp_cp_ret0=f((?{}(&_tmp_cp1, y) , _tmp_cp1)), _tmp_cp_ret0; |
---|
1316 | ^?{}(&_tmp_cp_ret0); // return value |
---|
1317 | ^?{}(&_tmp_cp1); // argument 1 |
---|
1318 | |
---|
1319 | struct A _tmp_cp2; // argument 1 |
---|
1320 | struct A _tmp_cp_ret1; // return value |
---|
1321 | _tmp_cp_ret1=f((?{}(&_tmp_cp2, z), _tmp_cp2)), _tmp_cp_ret1; |
---|
1322 | ^?{}(&_tmp_cp_ret1); // return value |
---|
1323 | ^?{}(&_tmp_cp2); // argument 1 |
---|
1324 | ^?{}(&y); |
---|
1325 | \end{cfacode} |
---|
1326 | |
---|
1327 | 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. |
---|
1328 | 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. |
---|
1329 | This approach works out most of the time, because typically destructors need to only access the fields of the object and recursively destroy. |
---|
1330 | 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. |
---|
1331 | Thus is it not safe to rely on an object's @this@ pointer to remain constant throughout execution of the program. |
---|
1332 | \begin{cfacode} |
---|
1333 | A * external_data[32]; |
---|
1334 | int ext_count; |
---|
1335 | struct A; |
---|
1336 | void ?{}(A * a) { |
---|
1337 | // ... |
---|
1338 | external_data[ext_count++] = a; |
---|
1339 | } |
---|
1340 | void ^?{}(A * a) { |
---|
1341 | for (int i = 0; i < ext_count) { |
---|
1342 | if (a == external_data[i]) { // may never be true |
---|
1343 | // ... |
---|
1344 | } |
---|
1345 | } |
---|
1346 | } |
---|
1347 | \end{cfacode} |
---|
1348 | In the above example, a global array of pointers is used to keep track of all of the allocated @A@ objects. |
---|
1349 | 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. |
---|
1350 | |
---|
1351 | This problem could be solved in the translator by mutating the function signatures so that the return value is moved into the parameter list. |
---|
1352 | For example, the translator could restructure the code like so |
---|
1353 | \begin{cfacode} |
---|
1354 | void f(struct A x, struct A * _retval_f){ |
---|
1355 | ?{}(_retval_f, x); // construct directly into caller's stack frame |
---|
1356 | } |
---|
1357 | |
---|
1358 | struct A y; |
---|
1359 | ?{}(&y); |
---|
1360 | struct A z = { 0 }; |
---|
1361 | |
---|
1362 | struct A _tmp_cp1; // argument 1 |
---|
1363 | struct A _tmp_cp_ret0; // return value |
---|
1364 | f((?{}(&_tmp_cp1, y) , _tmp_cp1), &_tmp_cp_ret0), _tmp_cp_ret0; |
---|
1365 | ^?{}(&_tmp_cp_ret0); // return value |
---|
1366 | ^?{}(&_tmp_cp1); // argument 1 |
---|
1367 | \end{cfacode} |
---|
1368 | This transformation provides @f@ with the address of the return variable so that it can be constructed into directly. |
---|
1369 | 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}. |
---|
1370 | 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. |
---|
1371 | \begin{cfacode} |
---|
1372 | struct A { int v; }; |
---|
1373 | A x; // unmanaged |
---|
1374 | { |
---|
1375 | void ?{}(A * a) { ... } |
---|
1376 | void ^?{}(A * a) { ... } |
---|
1377 | A y; // managed |
---|
1378 | } |
---|
1379 | A z; // unmanaged |
---|
1380 | \end{cfacode} |
---|
1381 | 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. |
---|
1382 | Even with this change, it would still be possible to declare backwards compatible function prototypes with an @extern "C"@ block, which allows for the definition of C-compatible functions within \CFA code, however this would require actual changes to the way code inside of an @extern "C"@ function is generated as compared with normal code generation. |
---|
1383 | Furthermore, it isn't possible to overload C functions, so using @extern "C"@ to declare functions is of limited use. |
---|
1384 | |
---|
1385 | 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. |
---|
1386 | Ideally, structs should be manageable by default, since otherwise the default case becomes more verbose. |
---|
1387 | This means that in general, function signatures would have to be rewritten, and in a select few cases the signatures would not be rewritten. |
---|
1388 | \begin{cfacode} |
---|
1389 | __attribute__((manageable)) struct A { ... }; // can declare constructors |
---|
1390 | __attribute__((unmanageable)) struct B { ... }; // cannot declare constructors |
---|
1391 | struct C { ... }; // can declare constructors |
---|
1392 | |
---|
1393 | A f(); // rewritten void f(A *); |
---|
1394 | B g(); // not rewritten |
---|
1395 | C h(); // rewritten void h(C *); |
---|
1396 | \end{cfacode} |
---|
1397 | An alternative is to instead make the attribute \emph{identifiable}, which states that objects of this type use the @this@ parameter as an identity. |
---|
1398 | 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. |
---|
1399 | Furthermore, no restrictions would need to be placed on whether objects can be constructed. |
---|
1400 | \begin{cfacode} |
---|
1401 | __attribute__((identifiable)) struct A { ... }; // can declare constructors |
---|
1402 | struct B { ... }; // can declare constructors |
---|
1403 | |
---|
1404 | A f(); // rewritten void f(A *); |
---|
1405 | B g(); // not rewritten |
---|
1406 | \end{cfacode} |
---|
1407 | |
---|
1408 | Ultimately, this is the type of transformation that a real compiler would make when generating assembly code. |
---|
1409 | 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. |
---|
1410 | As such, it has been decided that this issue is not currently a priority. |
---|
1411 | |
---|
1412 | \section{Implementation} |
---|
1413 | \subsection{Array Initialization} |
---|
1414 | Arrays are a special case in the C type system. |
---|
1415 | C arrays do not carry around their size, making it impossible to write a standalone \CFA function that constructs or destructs an array while maintaining the standard interface for constructors and destructors. |
---|
1416 | Instead, \CFA defines the initialization and destruction of an array recursively. |
---|
1417 | That is, when an array is defined, each of its elements is constructed in order from element 0 up to element $n-1$. |
---|
1418 | When an array is to be implicitly destructed, each of its elements is destructed in reverse order from element $n-1$ down to element 0. |
---|
1419 | As in C, it is possible to explicitly provide different initializers for each element of the array through array initialization syntax. |
---|
1420 | In this case, each of the initializers is taken in turn to construct a subsequent element of the array. |
---|
1421 | If too many initializers are provided, only the initializers up to N are actually used. |
---|
1422 | If too few initializers are provided, then the remaining elements are default constructed. |
---|
1423 | |
---|
1424 | For example, given the following code. |
---|
1425 | \begin{cfacode} |
---|
1426 | struct X { |
---|
1427 | int x, y, z; |
---|
1428 | }; |
---|
1429 | void f() { |
---|
1430 | X x[10] = { { 1, 2, 3 }, { 4 }, { 7, 8 } }; |
---|
1431 | } |
---|
1432 | \end{cfacode} |
---|
1433 | The following code is generated for @f@. |
---|
1434 | \begin{cfacode} |
---|
1435 | void f(){ |
---|
1436 | struct X x[((long unsigned int )10)]; |
---|
1437 | // construct x |
---|
1438 | { |
---|
1439 | int _index0 = 0; |
---|
1440 | // construct with explicit initializers |
---|
1441 | { |
---|
1442 | if (_index0<10) ?{}(&x[_index0], 1, 2, 3); |
---|
1443 | ++_index0; |
---|
1444 | if (_index0<10) ?{}(&x[_index0], 4); |
---|
1445 | ++_index0; |
---|
1446 | if (_index0<10) ?{}(&x[_index0], 7, 8); |
---|
1447 | ++_index0; |
---|
1448 | } |
---|
1449 | |
---|
1450 | // default construct remaining elements |
---|
1451 | for (;_index0<10;++_index0) { |
---|
1452 | ?{}(&x[_index0]); |
---|
1453 | } |
---|
1454 | } |
---|
1455 | // destruct x |
---|
1456 | { |
---|
1457 | int _index1 = 10-1; |
---|
1458 | for (;_index1>=0;--_index1) { |
---|
1459 | ^?{}(&x[_index1]); |
---|
1460 | } |
---|
1461 | } |
---|
1462 | } |
---|
1463 | \end{cfacode} |
---|
1464 | Multidimensional arrays require more complexity. |
---|
1465 | For example, a two dimensional array |
---|
1466 | \begin{cfacode} |
---|
1467 | void g() { |
---|
1468 | X x[10][10] = { |
---|
1469 | { { 1, 2, 3 }, { 4 } }, // x[0] |
---|
1470 | { { 7, 8 } } // x[1] |
---|
1471 | }; |
---|
1472 | }\end{cfacode} |
---|
1473 | Generates the following |
---|
1474 | \begin{cfacode} |
---|
1475 | void g(){ |
---|
1476 | struct X x[10][10]; |
---|
1477 | // construct x |
---|
1478 | { |
---|
1479 | int _index0 = 0; |
---|
1480 | for (;_index0<10;++_index0) { |
---|
1481 | { |
---|
1482 | int _index1 = 0; |
---|
1483 | // construct with explicit initializers |
---|
1484 | { |
---|
1485 | switch ( _index0 ) { |
---|
1486 | case 0: |
---|
1487 | // construct first array |
---|
1488 | if ( _index1<10 ) ?{}(&x[_index0][_index1], 1, 2, 3); |
---|
1489 | ++_index1; |
---|
1490 | if ( _index1<10 ) ?{}(&x[_index0][_index1], 4); |
---|
1491 | ++_index1; |
---|
1492 | break; |
---|
1493 | case 1: |
---|
1494 | // construct second array |
---|
1495 | if ( _index1<10 ) ?{}(&x[_index0][_index1], 7, 8); |
---|
1496 | ++_index1; |
---|
1497 | break; |
---|
1498 | } |
---|
1499 | } |
---|
1500 | // default construct remaining elements |
---|
1501 | for (;_index1<10;++_index1) { |
---|
1502 | ?{}(&x[_index0][_index1]); |
---|
1503 | } |
---|
1504 | } |
---|
1505 | } |
---|
1506 | } |
---|
1507 | // destruct x |
---|
1508 | { |
---|
1509 | int _index2 = 10-1; |
---|
1510 | for (;_index2>=0;--_index2) { |
---|
1511 | { |
---|
1512 | int _index3 = 10-1; |
---|
1513 | for (;_index3>=0;--_index3) { |
---|
1514 | ^?{}(&x[_index2][_index3]); |
---|
1515 | } |
---|
1516 | } |
---|
1517 | } |
---|
1518 | } |
---|
1519 | } |
---|
1520 | \end{cfacode} |
---|
1521 | % It is possible to generate slightly simpler code for the switch cases, since the value of @_index1@ is known at compile-time within each case, however the procedure for generating constructor calls is complicated. |
---|
1522 | % It is simple to remove the increment statements for @_index1@, but it is not simple to remove the |
---|
1523 | %% technically, it's not hard either. I could easily downcast and change the second argument to ?[?], but is it really necessary/worth it?? |
---|
1524 | |
---|
1525 | \subsection{Global Initialization} |
---|
1526 | In standard C, global variables can only be initialized to compile-time constant expressions. |
---|
1527 | This places strict limitations on the programmer's ability to control the default values of objects. |
---|
1528 | In \CFA, constructors and destructors are guaranteed to be run on global objects, allowing arbitrary code to be run before and after the execution of the main routine. |
---|
1529 | By default, objects within a translation unit are constructed in declaration order, and destructed in the reverse order. |
---|
1530 | The default order of construction of objects amongst translation units is unspecified. |
---|
1531 | % TODO: not yet implemented, but g++ provides attribute init_priority, which allows specifying the order of global construction on a per object basis |
---|
1532 | % https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html#C_002b_002b-Attributes |
---|
1533 | % 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 |
---|
1534 | 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 | |
---|
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. % CITE: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes |
---|
1537 | A similar function is generated with the \emph{destructor} attribute, which handles all global destructor calls. |
---|
1538 | 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 teardown routines. |
---|
1540 | |
---|
1541 | For example, given the following global declarations. |
---|
1542 | \begin{cfacode} |
---|
1543 | struct X { |
---|
1544 | int y, z; |
---|
1545 | }; |
---|
1546 | void ?{}(X *); |
---|
1547 | void ?{}(X *, int, int); |
---|
1548 | void ^?{}(X *); |
---|
1549 | |
---|
1550 | X a; |
---|
1551 | X b = { 10, 3 }; |
---|
1552 | \end{cfacode} |
---|
1553 | The following code is generated. |
---|
1554 | \begin{cfacode} |
---|
1555 | __attribute__ ((constructor)) static void _init_global_ctor(void){ |
---|
1556 | ?{}(&a); |
---|
1557 | ?{}(&b, 10, 3); |
---|
1558 | } |
---|
1559 | __attribute__ ((destructor)) static void _destroy_global_ctor(void){ |
---|
1560 | ^?{}(&b); |
---|
1561 | ^?{}(&a); |
---|
1562 | } |
---|
1563 | \end{cfacode} |
---|
1564 | |
---|
1565 | \subsection{Static Local Variables} |
---|
1566 | In standard C, it is possible to mark variables that are local to a function with the @static@ storage class. |
---|
1567 | 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?? |
---|
1568 | 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. |
---|
1569 | |
---|
1570 | Yet again, this rule is too restrictive for a language with constructors and destructors. |
---|
1571 | 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. |
---|
1572 | 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. |
---|
1573 | Local objects with @static@ storage class are only implicitly constructed and destructed once for the duration of the program. |
---|
1574 | The object is constructed when its declaration is reached for the first time. |
---|
1575 | The object is destructed once at the end of the program. |
---|
1576 | |
---|
1577 | Construction of @static@ local objects is implemented via an accompanying @static bool@ variable, which records whether the variable has already been constructed. |
---|
1578 | A conditional branch checks the value of the companion @bool@, and if the variable has not yet been constructed then the object is constructed. |
---|
1579 | 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. |
---|
1580 | Since the parameter to @atexit@ is a parameter-less function, some additional tweaking is required. |
---|
1581 | First, the @static@ variable must be hoisted up to global scope and uniquely renamed to prevent name clashes with other global objects. |
---|
1582 | Second, a function is built which calls the destructor for the newly hoisted variable. |
---|
1583 | Finally, the newly generated function is registered with @atexit@, instead of registering the destructor directly. |
---|
1584 | 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. |
---|
1585 | |
---|
1586 | Extending the previous example |
---|
1587 | \begin{cfacode} |
---|
1588 | int f(int x) { |
---|
1589 | static X a; |
---|
1590 | static X b = { x, x }; // depends on parameter value |
---|
1591 | static X c = b; // depends on local variable |
---|
1592 | } |
---|
1593 | \end{cfacode} |
---|
1594 | Generates the following. |
---|
1595 | \begin{cfacode} |
---|
1596 | static struct X a_static_var0; |
---|
1597 | static void __a_dtor_atexit0(void){ |
---|
1598 | ((void)^?{}(((struct X *)(&a_static_var0)))); |
---|
1599 | } |
---|
1600 | static struct X b_static_var1; |
---|
1601 | static void __b_dtor_atexit1(void){ |
---|
1602 | ((void)^?{}(((struct X *)(&b_static_var1)))); |
---|
1603 | } |
---|
1604 | static struct X c_static_var2; |
---|
1605 | static void __c_dtor_atexit2(void){ |
---|
1606 | ((void)^?{}(((struct X *)(&c_static_var2)))); |
---|
1607 | } |
---|
1608 | int f(int x){ |
---|
1609 | int _retval_f; |
---|
1610 | __attribute__ ((unused)) static void *_dummy0; |
---|
1611 | static _Bool __a_uninitialized = 1; |
---|
1612 | if ( __a_uninitialized ) { |
---|
1613 | ((void)?{}(((struct X *)(&a_static_var0)))); |
---|
1614 | ((void)(__a_uninitialized=0)); |
---|
1615 | ((void)atexit(__a_dtor_atexit0)); |
---|
1616 | } |
---|
1617 | |
---|
1618 | __attribute__ ((unused)) static void *_dummy1; |
---|
1619 | static _Bool __b_uninitialized = 1; |
---|
1620 | if ( __b_uninitialized ) { |
---|
1621 | ((void)?{}(((struct X *)(&b_static_var1)), x, x)); |
---|
1622 | ((void)(__b_uninitialized=0)); |
---|
1623 | ((void)atexit(__b_dtor_atexit1)); |
---|
1624 | } |
---|
1625 | |
---|
1626 | __attribute__ ((unused)) static void *_dummy2; |
---|
1627 | static _Bool __c_uninitialized = 1; |
---|
1628 | if ( __c_uninitialized ) { |
---|
1629 | ((void)?{}(((struct X *)(&c_static_var2)), b_static_var1)); |
---|
1630 | ((void)(__c_uninitialized=0)); |
---|
1631 | ((void)atexit(__c_dtor_atexit2)); |
---|
1632 | } |
---|
1633 | } |
---|
1634 | \end{cfacode} |
---|
1635 | |
---|
1636 | \subsection{Constructor Expressions} |
---|
1637 | In \CFA, it is possible to use a constructor as an expression. |
---|
1638 | Like other operators, the function name @?{}@ matches its operator syntax. |
---|
1639 | For example, @(&x){}@ calls the default constructor on the variable @x@, and produces @&x@ as a result. |
---|
1640 | 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. |
---|
1641 | A key example is the use of constructor expressions to initialize the result of a call to standard C routine @malloc@. |
---|
1642 | \begin{cfacode} |
---|
1643 | struct X { ... }; |
---|
1644 | void ?{}(X *, double); |
---|
1645 | X * x = malloc(sizeof(X)){ 1.5 }; |
---|
1646 | \end{cfacode} |
---|
1647 | In this example, @malloc@ dynamically allocates storage and initializes it using a constructor, all before assigning it into the variable @x@. |
---|
1648 | 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. |
---|
1649 | \begin{cfacode} |
---|
1650 | X * x = malloc(sizeof(X)); |
---|
1651 | x{ 1.5 }; |
---|
1652 | \end{cfacode} |
---|
1653 | 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. |
---|
1654 | 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. |
---|
1655 | 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. |
---|
1656 | The previous example generates the following code. |
---|
1657 | \begin{cfacode} |
---|
1658 | struct X *_tmp_ctor; |
---|
1659 | struct X *x = ?{}((_tmp_ctor=((_tmp_cp_ret0= |
---|
1660 | malloc(sizeof(struct X))), _tmp_cp_ret0))), 1.5), _tmp_ctor); |
---|
1661 | \end{cfacode} |
---|
1662 | 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. |
---|
1663 | |
---|
1664 | It is also possible to use operator syntax with destructors. |
---|
1665 | 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. |
---|
1666 | For example, \lstinline!^(&x){}! calls the destructor on the variable @x@. |
---|