source: doc/rob_thesis/tuples.tex @ fbd7ad6

Last change on this file since fbd7ad6 was 7493339, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

incorporate Peter's feedback, handle many TODOs

  • Property mode set to 100644
File size: 45.6 KB
6% TODO: no passing input parameters by assignment, instead will have reference types => this is not a very C-like model and greatly complicates syntax for likely little gain (and would cause confusion with already supported return-by-reference)
7% TODO: benefits (conclusion) by Till: reduced number of variables and statements; no specified order of execution for multiple assignment (more optimzation freedom); can store parameter lists in variable; MRV routines (natural code); more convenient assignment statements; simple and efficient access of record fields; named return values more legible and efficient in use of storage
9\section{Multiple-Return-Value Functions}
11In standard C, functions can return at most one value.
12This restriction results in code which emulates functions with multiple return values by \emph{aggregation} or by \emph{aliasing}.
13In the former situation, the function designer creates a record type that combines all of the return values into a single type.
14For example, consider a function returning the most frequently occuring letter in a string, and its frequency.
15% TODO: consider simplifying the example!
16%   Two things I like about this example:
17%   * it uses different types to illustrate why an array is insufficient (this is not necessary, but is nice)
18%   * it's complicated enough to show the uninitialized pitfall that exists in the aliasing example.
19%   Still, it may be a touch too complicated. Is there a simpler example with these two properties?
21struct mf_ret {
22  int freq;
23  char ch;
26struct mf_ret most_frequent(const char * str) {
27  char freqs [26] = { 0 };
28  struct mf_ret ret = { 0, 'a' };
29  for (int i = 0; str[i] != '\0'; ++i) {
30    if (isalpha(str[i])) {        // only count letters
31      int ch = tolower(str[i]);   // convert to lower case
32      int idx = ch-'a';
33      if (++freqs[idx] > ret.freq) {  // update on new max
34        ret.freq = freqs[idx];
35 = ch;
36      }
37    }
38  }
39  return ret;
42const char * str = "hello world";
43struct mf_ret ret = most_frequent(str);
44printf("%s -- %d %c\n", str, ret.freq,;
46Of note, the designer must come up with a name for the return type and for each of its fields.
47Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model.
48That is, adding another named type creates another association in the programmer's mind that needs to be kept track of when reading and writing code.
49As such, this technique is effective when used sparingly, but can quickly get out of hand if many functions need to return different combinations of types.
51In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters.
52The pointer parameters are assigned inside of the routine body to emulate a return.
53Using the same example,
55int most_frequent(const char * str, char * ret_ch) {
56  char freqs [26] = { 0 };
57  int ret_freq = 0;
58  for (int i = 0; str[i] != '\0'; ++i) {
59    if (isalpha(str[i])) {        // only count letters
60      int ch = tolower(str[i]);   // convert to lower case
61      int idx = ch-'a';
62      if (++freqs[idx] > ret_freq) {  // update on new max
63        ret_freq = freqs[idx];
64        *ret_ch = ch;   // assign to out parameter
65      }
66    }
67  }
68  return ret_freq;  // only one value returned directly
71const char * str = "hello world";
72char ch;                            // pre-allocate return value
73int freq = most_frequent(str, &ch); // pass return value as out parameter
74printf("%s -- %d %c\n", str, freq, ch);
76Notably, using this approach, the caller is directly responsible for allocating storage for the additional temporary return values, which complicates the call site with a sequence of variable declarations leading up to the call.
77Also, while a disciplined use of @const@ can give clues about whether a pointer parameter is going to be used as an out parameter, it is not immediately obvious from only the routine signature whether the callee expects such a parameter to be initialized before the call.
78Furthermore, while many C routines that accept pointers are designed so that it is safe to pass @NULL@ as a parameter, there are many C routines that are not null-safe.
79On a related note, C does not provide a standard mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler.
80There is a subtle bug in the previous example, in that @ret_ch@ is never assigned for a string that does not contain any letters, which can lead to undefined behaviour.
81As with the previous approach, this technique can simulate multiple return values, but in practice it is verbose and error prone.
83In \CFA, functions can be declared to return multiple values with an extension to the function declaration syntax.
84Multiple return values are declared as a comma-separated list of types in square brackets in the same location that the return type appears in standard C function declarations.
85The ability to return multiple values from a function requires a new syntax for the return statement.
86For consistency, the return statement in \CFA accepts a comma-separated list of expressions in square brackets.
87The expression resolution phase of the \CFA translator ensures that the correct form is used depending on the values being returned and the return type of the current function.
88A multiple-returning function with return type @T@ can return any expression that is implicitly convertible to @T@.
89Using the running example, the @most_frequent@ function can be written in using multiple return values as such,
91[int, char] most_frequent(const char * str) {
92  char freqs [26] = { 0 };
93  int ret_freq = 0;
94  char ret_ch = 'a';
95  for (int i = 0; str[i] != '\0'; ++i) {
96    if (isalpha(str[i])) {        // only count letters
97      int ch = tolower(str[i]);   // convert to lower case
98      int idx = ch-'a';
99      if (++freqs[idx] > ret_freq) {  // update on new max
100        ret_freq = freqs[idx];
101        ret_ch = ch;
102      }
103    }
104  }
105  return [ret_freq, ret_ch];
108This approach provides the benefits of compile-time checking for appropriate return statements as in aggregation, but without the required verbosity of declaring a new named type, which precludes the bug seen with out parameters.
110The addition of multiple-return-value functions necessitates a syntax for accepting multiple values at the call-site.
111The simplest mechanism for retaining a return value in C is variable assignment.
112By assigning the return value into a variable, its value can be retrieved later at any point in the program.
113As such, \CFA allows assigning multiple values from a function into multiple variables, using a square-bracketed list of lvalue expressions on the left side.
115const char * str = "hello world";
116int freq;
117char ch;
118[freq, ch] = most_frequent(str);  // assign into multiple variables
119printf("%s -- %d %c\n", str, freq, ch);
121It is also common to use a function's output as the input to another function.
122\CFA also allows this case, without any new syntax.
123When a function call is passed as an argument to another call, the expression resolver attempts to find the best match of actual arguments to formal parameters given all of the possible expression interpretations in the current scope \cite{Bilson03}.
124For example,
126void process(int);       // (1)
127void process(char);      // (2)
128void process(int, char); // (3)
129void process(char, int); // (4)
131process(most_frequent("hello world"));  // selects (3)
133In this case, there is only one option for a function named @most_frequent@ that takes a string as input.
134This function returns two values, one @int@ and one @char@.
135There are four options for a function named @process@, but only two that accept two arguments, and of those the best match is (3), which is also an exact match.
136This expression first calls @most_frequent("hello world")@, which produces the values @3@ and @'l'@, which are fed directly to the first and second parameters of (3), respectively.
138\section{Tuple Expressions}
139Multiple-return-value functions provide \CFA with a new syntax for expressing a combination of expressions in the return statement and a combination of types in a function signature.
140These notions can be generalized to provide \CFA with \emph{tuple expressions} and \emph{tuple types}.
141A tuple expression is an expression producing a fixed-size, ordered list of values of heterogeneous types.
142The type of a tuple expression is the tuple of the subexpression types, or a \emph{tuple type}.
143In \CFA, a tuple expression is denoted by a comma-separated list of expressions enclosed in square brackets.
144For example, the expression @[5, 'x', 10.5]@ has type @[int, char, double]@.
145The previous expression has 3 \emph{components}.
146Each component in a tuple expression can be any \CFA expression, including another tuple expression.
147The order of evaluation of the components in a tuple expression is unspecified, to allow a compiler the greatest flexibility for program optimization.
148It is, however, guaranteed that each component of a tuple expression is evaluated for side-effects, even if the result is not used.
149Multiple-return-value functions can equivalently be called \emph{tuple-returning functions}.
151\subsection{Tuple Variables}
152The call-site of the @most_frequent@ routine has a notable blemish, in that it required the preallocation of return variables in a manner similar to the aliasing example, since it is impossible to declare multiple variables of different types in the same declaration in standard C.
153In \CFA, it is possible to overcome this restriction by declaring a \emph{tuple variable}.
154\begin{cfacode}[emph=ret, emphstyle=\color{red}]
155const char * str = "hello world";
156[int, char] ret = most_frequent(str);  // initialize tuple variable
157printf("%s -- %d %c\n", str, ret);
159It is now possible to accept multiple values into a single piece of storage, in much the same way that it was previously possible to pass multiple values from one function call to another.
160These variables can be used in any of the contexts where a tuple expression is allowed, such as in the @printf@ function call.
161As in the @process@ example, the components of the tuple value are passed as separate parameters to @printf@, allowing very simple printing of tuple expressions.
162One way to access the individual components is with a simple assignment, as in previous examples.
164int freq;
165char ch;
166[freq, ch] = ret;
169In addition to variables of tuple type, it is also possible to have pointers to tuples, and arrays of tuples.
170Tuple types can be composed of any types, except for array types, since arrays do not carry their size around, which makes tuple assignment difficult when a tuple contains an array.
172[double, int] di;
173[double, int] * pdi
174[double, int] adi[10];
176This examples declares a variable of type @[double, int]@, a variable of type pointer to @[double, int]@, and an array of ten @[double, int]@.
178\subsection{Tuple Indexing}
179At times, it is desirable to access a single component of a tuple-valued expression without creating unnecessary temporary variables to assign to.
180Given a tuple-valued expression @e@ and a compile-time constant integer $i$ where $0 \leq i < n$, where $n$ is the number of components in @e@, @e.i@ accesses the $i$\textsuperscript{th} component of @e@.
181For example,
183[int, double] x;
184[char *, int] f();
185void g(double, int);
186[int, double] * p;
188int y = x.0;              // access int component of x
189y = f().1;                // access int component of f
190p->0 = 5;                 // access int component of tuple pointed-to by p
191g(x.1, x.0);              // rearrange x to pass to g
192double z = [x, f()].0.1;  // access second component of first component
193                          // of tuple expression
195As seen above, tuple-index expressions can occur on any tuple-typed expression, including tuple-returning functions, square-bracketed tuple expressions, and other tuple-index expressions, provided the retrieved component is also a tuple.
196This feature was proposed for \KWC but never implemented \cite[p.~45]{Till89}.
198\subsection{Flattening and Structuring}
199As evident in previous examples, tuples in \CFA do not have a rigid structure.
200In function call contexts, tuples support implicit flattening and restructuring conversions.
201Tuple flattening recursively expands a tuple into the list of its basic components.
202Tuple structuring packages a list of expressions into a value of tuple type.
204int f(int, int);
205int g([int, int]);
206int h(int, [int, int]);
207[int, int] x;
208int y;
210f(x);      // flatten
211g(y, 10);  // structure
212h(x, y);   // flatten & structure
214In \CFA, each of these calls is valid.
215In the call to @f@, @x@ is implicitly flattened so that the components of @x@ are passed as the two arguments to @f@.
216For the call to @g@, the values @y@ and @10@ are structured into a single argument of type @[int, int]@ to match the type of the parameter of @g@.
217Finally, in the call to @h@, @y@ is flattened to yield an argument list of length 3, of which the first component of @x@ is passed as the first parameter of @h@, and the second component of @x@ and @y@ are structured into the second argument of type @[int, int]@.
218The flexible structure of tuples permits a simple and expressive function call syntax to work seamlessly with both single- and multiple-return-value functions, and with any number of arguments of arbitrarily complex structure.
220In \KWC \cite{Buhr94a,Till89}, a precursor to \CFA, there were 4 tuple coercions: opening, closing, flattening, and structuring.
221Opening coerces a tuple value into a tuple of values, while closing converts a tuple of values into a single tuple value.
222Flattening coerces a nested tuple into a flat tuple, i.e. it takes a tuple with tuple components and expands it into a tuple with only non-tuple components.
223Structuring moves in the opposite direction, i.e. it takes a flat tuple value and provides structure by introducing nested tuple components.
225In \CFA, the design has been simplified to require only the two conversions previously described, which trigger only in function call and return situations.
226Specifically, the expression resolution algorithm examines all of the possible alternatives for an expression to determine the best match.
227In resolving a function call expression, each combination of function value and list of argument alternatives is examined.
228Given a particular argument list and function value, the list of argument alternatives is flattened to produce a list of non-tuple valued expressions.
229Then the flattened list of expressions is compared with each value in the function's parameter list.
230If the parameter's type is not a tuple type, then the current argument value is unified with the parameter type, and on success the next argument and parameter are examined.
231If the parameter's type is a tuple type, then the structuring conversion takes effect, recursively applying the parameter matching algorithm using the tuple's component types as the parameter list types.
232Assuming a successful unification, eventually the algorithm gets to the end of the tuple type, which causes all of the matching expressions to be consumed and structured into a tuple expression.
233For example, in
235int f(int, [double, int]);
236f([5, 10.2], 4);
238There is only a single definition of @f@, and 3 arguments with only single interpretations.
239First, the argument alternative list @[5, 10.2], 4@ is flattened to produce the argument list @5, 10.2, 4@.
240Next, the parameter matching algorithm begins, with $P = $@int@ and $A = $@int@, which unifies exactly.
241Moving to the next parameter and argument, $P = $@[double, int]@ and $A = $@double@.
242This time, the parameter is a tuple type, so the algorithm applies recursively with $P' = $@double@ and $A = $@double@, which unifies exactly.
243Then $P' = $@int@ and $A = $@double@, which again unifies exactly.
244At this point, the end of $P'$ has been reached, so the arguments @10.2, 4@ are structured into the tuple expression @[10.2, 4]@.
245Finally, the end of the parameter list $P$ has also been reached, so the final expression is @f(5, [10.2, 4])@.
247\section{Tuple Assignment}
249An assignment where the left side of the assignment operator has a tuple type is called tuple assignment.
250There are two kinds of tuple assignment depending on whether the right side of the assignment operator has a tuple type or a non-tuple type, called \emph{Multiple} and \emph{Mass} Assignment, respectively.
252int x;
253double y;
254[int, double] z;
255[y, x] = 3.14;  // mass assignment
256[x, y] = z;     // multiple assignment
257z = 10;         // mass assignment
258z = [x, y];     // multiple assignment
260Let $L_i$ for $i$ in $[0, n)$ represent each component of the flattened left side, $R_i$ represent each component of the flattened right side of a multiple assignment, and $R$ represent the right side of a mass assignment.
262For a multiple assignment to be valid, both tuples must have the same number of elements when flattened. Multiple assignment assigns $R_i$ to $L_i$ for each $i$.
263That is, @?=?(&$L_i$, $R_i$)@ must be a well-typed expression.
264In the previous example, @[x, y] = z@, @z@ is flattened into @z.0, z.1@, and the assignments @x = z.0@ and @y = z.1@ happen.
266A mass assignment assigns the value $R$ to each $L_i$.
267For a mass assignment to be valid, @?=?(&$L_i$, $R$)@ must be a well-typed expression.
268These semantics differ from C cascading assignment (e.g. @a=b=c@) in that conversions are applied to $R$ in each individual assignment, which prevents data loss from the chain of conversions that can happen during a cascading assignment.
269For example, @[y, x] = 3.14@ performs the assignments @y = 3.14@ and @x = 3.14@, which results in the value @3.14@ in @y@ and the value @3@ in @x@.
270On the other hand, the C cascading assignment @y = x = 3.14@ performs the assignments @x = 3.14@ and @y = x@, which results in the value @3@ in @x@, and as a result the value @3@ in @y@ as well.
272Both kinds of tuple assignment have parallel semantics, such that each value on the left side and right side is evaluated \emph{before} any assignments occur.
273As a result, it is possible to swap the values in two variables without explicitly creating any temporary variables or calling a function,
275int x = 10, y = 20;
276[x, y] = [y, x];
278After executing this code, @x@ has the value @20@ and @y@ has the value @10@.
280In \CFA, tuple assignment is an expression where the result type is the type of the left side of the assignment, as in normal assignment.
281That is, a tuple assignment produces the value of the left-hand side after assignment.
282These semantics allow cascading tuple assignment to work out naturally in any context where a tuple is permitted.
283These semantics are a change from the original tuple design in \KWC \cite{Till89}, wherein tuple assignment was a statement that allows cascading assignments as a special case.
284The \KWC semantics fix what was seen as a problem with assignment, wherein it can be used in many different locations, such as in function-call argument position. % TODO: remove??
285While permitting assignment as an expression does introduce the potential for subtle complexities, it is impossible to remove assignment expressions from \CFA without affecting backwards compatibility.
286Furthermore, there are situations where permitting assignment as an expression improves readability by keeping code succinct and reducing repetition, and complicating the definition of tuple assignment puts a greater cognitive burden on the user.
287In another language, tuple assignment as a statement could be reasonable, but it would be inconsistent for tuple assignment to be the only kind of assignment that is not an expression.
288In addition, \KWC permits the compiler to optimize tuple assignment as a block copy, since it does not support user-defined assignment operators.
289This optimization could be implemented in \CFA, but it requires the compiler to verify that the selected assignment operator is trivial.
291The following example shows multiple, mass, and cascading assignment used in one expression
293  int a, b;
294  double c, d;
295  [void] f([int, int]);
296  f([c, a] = [b, d] = 1.5);  // assignments in parameter list
298The tuple expression begins with a mass assignment of @1.5@ into @[b, d]@, which assigns @1.5@ into @b@, which is truncated to @1@, and @1.5@ into @d@, producing the tuple @[1, 1.5]@ as a result.
299That tuple is used as the right side of the multiple assignment (i.e., @[c, a] = [1, 1.5]@) that assigns @1@ into @c@ and @1.5@ into @a@, which is truncated to @1@, producing the result @[1, 1]@.
300Finally, the tuple @[1, 1]@ is used as an expression in the call to @f@.
302\subsection{Tuple Construction}
303Tuple construction and destruction follow the same rules and semantics as tuple assignment, except that in the case where there is no right side, the default constructor or destructor is called on each component of the tuple.
305struct S;
306void ?{}(S *);         // (1)
307void ?{}(S *, int);    // (2)
308void ?{}(S * double);  // (3)
309void ?{}(S *, S);      // (4)
311[S, S] x = [3, 6.28];  // uses (2), (3), specialized constructors
312[S, S] y;              // uses (1), (1), default constructor
313[S, S] z = x.0;        // uses (4), (4), copy constructor
315In this example, @x@ is initialized by the multiple constructor calls @?{}(&x.0, 3)@ and @?{}(&x.1, 6.28)@, while @y@ is initilaized by two default constructor calls @?{}(&y.0)@ and @?{}(&y.1)@.
316@z@ is initialized by mass copy constructor calls @?{}(&z.0, x.0)@ and @?{}(&z.1, x.0)@.
317Finally, @x@, @y@, and @z@ are destructed, i.e. the calls @^?{}(&x.0)@, @^?{}(&x.1)@, @^?{}(&y.0)@, @^?{}(&y.1)@, @^?{}(&z.0)@, and @^?{}(&z.1)@.
319It is possible to define constructors and assignment functions for tuple types that provide new semantics, if the existing semantics do not fit the needs of an application.
320For example, the function @void ?{}([T, U] *, S);@ can be defined to allow a tuple variable to be constructed from a value of type @S@.
322struct S { int x; double y; };
323void ?{}([int, double] * this, S s) {
324  this->0 = s.x;
325  this->1 = s.y;
328Due to the structure of generated constructors, it is possible to pass a tuple to a generated constructor for a type with a member prefix that matches the type of the tuple.
329For example,
331struct S { int x; double y; int z };
332[int, double] t;
333S s = t;
335The initialization of @s@ with @t@ works by default because @t@ is flattened into its components, which satisfies the generated field constructor @?{}(S *, int, double)@ to initialize the first two values.
337\section{Member-Access Tuple Expression}
339It is possible to access multiple fields from a single expression using a \emph{Member-Access Tuple Expression}.
340The result is a single tuple-valued expression whose type is the tuple of the types of the members.
341For example,
343struct S { int x; double y; char * z; } s;
344s.[x, y, z];
346Here, the type of @s.[x, y, z]@ is @[int, double, char *]@.
347A member tuple expression has the form @a.[x, y, z];@ where @a@ is an expression with type @T@, where @T@ supports member access expressions, and @x, y, z@ are all members of @T@ with types @T$_x$@, @T$_y$@, and @T$_z$@ respectively.
348Then the type of @a.[x, y, z]@ is @[T_x, T_y, T_z]@.
350Since tuple index expressions are a form of member-access expression, it is possible to use tuple-index expressions in conjunction with member tuple expressions to manually restructure a tuple (e.g., rearrange components, drop components, duplicate components, etc.).
352[int, int, long, double] x;
353void f(double, long);
355f(x.[0, 3]);          // f(x.0, x.3)
356x.[0, 1] = x.[1, 0];  // [x.0, x.1] = [x.1, x.0]
357[long, int, long] y = x.[2, 0, 2];
360It is possible for a member tuple expression to contain other member access expressions.
361For example,
363struct A { double i; int j; };
364struct B { int * k; short l; };
365struct C { int x; A y; B z; } v;
366v.[x, y.[i, j], z.k];
368This expression is equivalent to @[v.x, [v.y.i, v.y.j], v.z.k]@.
369That is, the aggregate expression is effectively distributed across the tuple, which allows simple and easy access to multiple components in an aggregate, without repetition.
370It is guaranteed that the aggregate expression to the left of the @.@ in a member tuple expression is evaluated exactly once.
371As such, it is safe to use member tuple expressions on the result of a side-effecting function.
373[int, float, double] f();
374[double, float] x = f().[2, 1];
377In \KWC, member tuple expressions are known as \emph{record field tuples} \cite{Till89}.
378Since \CFA permits these tuple-access expressions using structures, unions, and tuples, \emph{member tuple expression} or \emph{field tuple expression} is more appropriate.
380It is possible to extend member-access expressions further.
381Currently, a member-access expression whose member is a name requires that the aggregate is a structure or union, while a constant integer member requires the aggregate to be a tuple.
382In the interest of orthogonal design, \CFA could apply some meaning to the remaining combinations as well.
383For example,
385struct S { int x, y; } s;
386[S, S] z;
388s.x;  // access member
389z.0;  // access component
391s.1;  // ???
392z.y;  // ???
394One possiblity is for @s.1@ to select the second member of @s@.
395Under this interpretation, it becomes possible to not only access members of a struct by name, but also by position.
396Likewise, it seems natural to open this mechanism to enumerations as well, wherein the left side would be a type, rather than an expression.
397One benefit of this interpretation is familiar, since it is extremely reminiscent of tuple-index expressions.
398On the other hand, it could be argued that this interpretation is brittle in that changing the order of members or adding new members to a structure becomes a brittle operation.
399This problem is less of a concern with tuples, since modifying a tuple affects only the code that directly uses the tuple, whereas modifying a structure has far reaching consequences for every instance of the structure.
401As for @z.y@, a one interpretation is to extend the meaning of member tuple expressions.
402That is, currently the tuple must occur as the member, i.e. to the right of the dot.
403Allowing tuples to the left of the dot could distribute the member across the elements of the tuple, in much the same way that member tuple expressions distribute the aggregate across the member tuple.
404In this example, @z.y@ expands to @[z.0.y, z.1.y]@, allowing what is effectively a very limited compile-time field-sections map operation, where the argument must be a tuple containing only aggregates having a member named @y@.
405It is questionable how useful this would actually be in practice, since structures often do not have names in common with other structures, and further this could cause maintainability issues in that it encourages programmers to adopt very simple naming conventions to maximize the amount of overlap between different types.
406Perhaps more useful would be to allow arrays on the left side of the dot, which would likewise allow mapping a field access across the entire array, producing an array of the contained fields.
407The immediate problem with this idea is that C arrays do not carry around their size, which would make it impossible to use this extension for anything other than a simple stack allocated array.
409Supposing this feature works as described, it would be necessary to specify an ordering for the expansion of member-access expressions versus member-tuple expressions.
411struct { int x, y; };
412[S, S] z;
413z.[x, y];  // ???
414// => [z.0, z.1].[x, y]
415// => [z.0.x, z.0.y, z.1.x, z.1.y]
416// or
417// => [z.x, z.y]
418// => [[z.0, z.1].x, [z.0, z.1].y]
419// => [z.0.x, z.1.x, z.0.y, z.1.y]
421Depending on exactly how the two tuples are combined, different results can be achieved.
422As such, a specific ordering would need to be imposed to make this feature useful.
423Furthermore, this addition moves a member-tuple expression's meaning from being clear statically to needing resolver support, since the member name needs to be distributed appropriately over each member of the tuple, which could itself be a tuple.
425A second possibility is for \CFA to have named tuples, as they exist in Swift and D.
427typedef [int x, int y] Point2D;
428Point2D p1, p2;
429p1.x + p1.y + p2.x + p2.y;
430p1.0 + p1.1 + p2.0 + p2.1;  // equivalent
432In this simpler interpretation, a named tuple type carries with it a list of possibly empty identifiers.
433This approach fits naturally with the named return-value feature, and would likely go a long way towards implementing it.
435Ultimately, the first two extensions introduce complexity into the model, with relatively little peceived benefit, and so were dropped from consideration.
436Named tuples are a potentially useful addition to the language, provided they can be parsed with a reasonable syntax.
440In C, the cast operator is used to explicitly convert between types.
441In \CFA, the cast operator has a secondary use, which is type ascription.
442That is, a cast can be used to select the type of an expression when it is ambiguous, as in the call to an overloaded function.
444int f();     // (1)
445double f();  // (2)
447f();       // ambiguous - (1),(2) both equally viable
448(int)f();  // choose (2)
450Since casting is a fundamental operation in \CFA, casts need to be given a meaningful interpretation in the context of tuples.
451Taking a look at standard C provides some guidance with respect to the way casts should work with tuples.
453int f();
454void g();
456(void)f();  // valid, ignore results
457(int)g();   // invalid, void cannot be converted to int
459struct A { int x; };
460(struct A)f();  // invalid
462In C, line 4 is a valid cast, which calls @f@ and discards its result.
463On the other hand, line 5 is invalid, because @g@ does not produce a result, so requesting an @int@ to materialize from nothing is nonsensical.
464Finally, line 8 is also invalid, because in C casts only provide conversion between scalar types \cite[p.~91]{C11}.
465For consistency, this implies that any case wherein the number of components increases as a result of the cast is invalid, while casts that have the same or fewer number of components may be valid.
467Formally, a cast to tuple type is valid when $T_n \leq S_m$, where $T_n$ is the number of components in the target type and $S_m$ is the number of components in the source type, and for each $i$ in $[0, n)$, $S_i$ can be cast to $T_i$.
468Excess elements ($S_j$ for all $j$ in $[n, m)$) are evaluated, but their values are discarded so that they are not included in the result expression.
469This discarding naturally follows the way that a cast to void works in C.
471For example,
473  [int, int, int] f();
474  [int, [int, int], int] g();
476  ([int, double])f();           // (1)
477  ([int, int, int])g();         // (2)
478  ([void, [int, int]])g();      // (3)
479  ([int, int, int, int])g();    // (4)
480  ([int, [int, int, int]])g();  // (5)
483(1) discards the last element of the return value and converts the second element to type double.
484Since @int@ is effectively a 1-element tuple, (2) discards the second component of the second element of the return value of @g@.
485If @g@ is free of side effects, this is equivalent to @[(int)(g().0), (int)(g().1.0), (int)(g().2)]@.
486Since @void@ is effectively a 0-element tuple, (3) discards the first and third return values, which is effectively equivalent to @[(int)(g().1.0), (int)(g().1.1)]@).
488% will this always hold true? probably, as constructors should give all of the conversion power we need. if casts become function calls, what would they look like? would need a way to specify the target type, which seems awkward. Also, C++ basically only has this because classes are closed to extension, while we don't have that problem (can have floating constructors for any type).
489Note that a cast is not a function call in \CFA, so flattening and structuring conversions do not occur for cast expressions.
490As such, (4) is invalid because the cast target type contains 4 components, while the source type contains only 3.
491Similarly, (5) is invalid because the cast @([int, int, int])(g().1)@ is invalid.
492That is, it is invalid to cast @[int, int]@ to @[int, int, int]@.
495Due to the implicit flattening and structuring conversions involved in argument passing, @otype@ and @dtype@ parameters are restricted to matching only with non-tuple types.
497forall(otype T, dtype U)
498void f(T x, U * y);
500f([5, "hello"]);
502In this example, @[5, "hello"]@ is flattened, so that the argument list appears as @5, "hello"@.
503The argument matching algorithm binds @T@ to @int@ and @U@ to @const char@, and calls the function as normal.
505Tuples can contain otype and dtype components.
506For example, a plus operator can be written to add two triples of a type together.
508forall(otype T | { T ?+?(T, T); })
509[T, T, T] ?+?([T, T, T] x, [T, T, T] y) {
510  return [x.0+y.0, x.1+y.1, x.2+y.2];
512[int, int, int] x;
513int i1, i2, i3;
514[i1, i2, i3] = x + ([10, 20, 30]);
516Note that due to the implicit tuple conversions, this function is not restricted to the addition of two triples.
517For example, these expressions also succeed and produce the same value.
518A call to this plus operator type checks as long as a total of 6 non-tuple arguments are passed after flattening, and all of the arguments have a common type that can bind to @T@, with a pairwise @?+?@ over @T@.
520([x.0, x.1]) + ([x.2, 10, 20, 30]);  // x + ([10, 20, 30])
521x.0 + ([x.1, x.2, 10, 20, 30]);      // x + ([10, 20, 30])
523This presents a potential problem if structure is important, as these three expressions look like they should have different meanings.
524Furthermore, these calls can be made ambiguous by adding seemingly different functions.
526forall(otype T | { T ?+?(T, T); })
527[T, T, T] ?+?([T, T] x, [T, T, T, T]);
528forall(otype T | { T ?+?(T, T); })
529[T, T, T] ?+?(T x, [T, T, T, T, T]);
531It is also important to note that these calls could be disambiguated if the function return types were different, as they likely would be for a reasonable implementation of @?+?@, since the return type is used in overload resolution.
532Still, these semantics are a deficiency of the current argument matching algorithm, and depending on the function, differing return values may not always be appropriate.
533These issues could be rectified by applying an appropriate cost to the structuring and flattening conversions, which are currently 0-cost conversions.
534Care would be needed in this case to ensure that exact matches do not incur such a cost.
536void f([int, int], int, int);
538f([0, 0], 0, 0);    // no cost
539f(0, 0, 0, 0);      // cost for structuring
540f([0, 0,], [0, 0]); // cost for flattening
541f([0, 0, 0], 0);    // cost for flattening and structuring
544Until this point, it has been assumed that assertion arguments must match the parameter type exactly, modulo polymorphic specialization (i.e., no implicit conversions are applied to assertion arguments).
545This decision presents a conflict with the flexibility of tuples.
546\subsection{Assertion Inference}
548int f([int, double], double);
549forall(otype T, otype U | { T f(T, U, U); })
550void g(T, U);
551g(5, 10.21);
553If assertion arguments must match exactly, then the call to @g@ cannot be resolved, since the expected type of @f@ is flat, while the only @f@ in scope requires a tuple type.
554Since tuples are fluid, this requirement reduces the usability of tuples in polymorphic code.
555To ease this pain point, function parameter and return lists are flattened for the purposes of type unification, which allows the previous example to pass expression resolution.
557This relaxation is made possible by extending the existing thunk generation scheme, as described by Bilson \cite{Bilson03}.
558Now, whenever a candidate's parameter structure does not exactly match the formal parameter's structure, a thunk is generated to specialize calls to the actual function.
560int _thunk(int _p0, double _p1, double _p2) {
561  return f([_p0, _p1], _p2);
564Essentially, this provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
567Tuples are implemented in the \CFA translator via a transformation into generic types.
568The first time an $N$-tuple is seen for each $N$ in a scope, a generic type with $N$ type parameters is generated.
569For example,
571[int, int] f() {
572  [double, double] x;
573  [int, double, int] y;
576Is transformed into
578forall(dtype T0, dtype T1 | sized(T0) | sized(T1))
579struct _tuple2 {  // generated before the first 2-tuple
580  T0 field_0;
581  T1 field_1;
583_tuple2_(int, int) f() {
584  _tuple2_(double, double) x;
585  forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2))
586  struct _tuple3 {  // generated before the first 3-tuple
587    T0 field_0;
588    T1 field_1;
589    T2 field_2;
590  };
591  _tuple3_(int, double, int) y;
595Tuple expressions are then simply converted directly into compound literals
597[5, 'x', 1.24];
601(_tuple3_(int, char, double)){ 5, 'x', 1.24 };
604Since tuples are essentially structures, tuple indexing expressions are just field accesses.
606void f(int, [double, char]);
607[int, double] x;
610printf("%d %g\n", x);
611f(x, 'z');
613Is transformed into
615void f(int, _tuple2_(double, char));
616_tuple2_(int, double) x;
619printf("%d %g\n", x.field_0, x.field_1);
620f(x.field_0, (_tuple2){ x.field_1, 'z' });
622Note that due to flattening, @x@ used in the argument position is converted into the list of its fields.
623In the call to @f@, the second and third argument components are structured into a tuple argument.
625Expressions that may contain side effects are made into \emph{unique expressions} before being expanded by the flattening conversion.
626Each unique expression is assigned an identifier and is guaranteed to be executed exactly once.
628void g(int, double);
629[int, double] h();
632Interally, this is converted to psuedo-\CFA
634void g(int, double);
635[int, double] h();
636lazy [int, double] unq<0> = h();
637g(unq<0>.0, unq<0>.1);
639That is, the function @h@ is evaluated lazily and its result is stored for subsequent accesses.
640Ultimately, unique expressions are converted into two variables and an expression.
642void g(int, double);
643[int, double] h();
645_Bool _unq0_finished_ = 0;
646[int, double] _unq0;
648  (_unq0_finished_ ? _unq0 : (_unq0 = h(), _unq0_finished_ = 1, _unq0)).0,
649  (_unq0_finished_ ? _unq0 : (_unq0 = h(), _unq0_finished_ = 1, _unq0)).1,
652Since argument evaluation order is not specified by the C programming language, this scheme is built to work regardless of evaluation order.
653The first time a unique expression is executed, the actual expression is evaluated and the accompanying boolean is set to true.
654Every subsequent evaluation of the unique expression then results in an access to the stored result of the actual expression.
656Currently, the \CFA translator has a very broad, imprecise definition of impurity (side-effects), where any function call is assumed to be impure.
657This notion could be made more precise for certain intrinsic, autogenerated, and builtin functions, and could analyze function bodies, when they are available, to recursively detect impurity, to eliminate some unique expressions.
658It is possible that lazy evaluation could be exposed to the user through a lazy keyword with little additional effort.
660Tuple member expressions are recursively expanded into a list of member access expressions.
662[int, [double, int, double], int]] x;
663x.[0, 1.[0, 2]];
665which becomes
667[x.0, [x.1.0, x.1.2]];
669Tuple-member expressions also take advantage of unique expressions in the case of possible impurity.
671Finally, the various kinds of tuple assignment, constructors, and destructors generate GNU C statement expressions.
672For example, a mass assignment
674int x, z;
675double y;
676[double, double] f();
678[x, y, z] = 1.5;            // mass assignment
680Generates the following
682// [x, y, z] = 1.5;
683_tuple3_(int, double, int) _tmp_stmtexpr_ret0;
685  // assign LHS address temporaries
686  int *__massassign_L0 = &x;    // ?{}
687  double *__massassign_L1 = &y; // ?{}
688  int *__massassign_L2 = &z;    // ?{}
690  // assign RHS value temporary
691  double __massassign_R0 = 1.5; // ?{}
693  ({ // tuple construction - construct statement expr return variable
694    // assign LHS address temporaries
695    int *__multassign_L0 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
696    double *__multassign_L1 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
697    int *__multassign_L2 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
699    // assign RHS value temporaries and perform mass assignment to L0, L1, L2
700    int __multassign_R0 = (*__massassign_L0=(int)__massassign_R0);   // ?{}
701    double __multassign_R1 = (*__massassign_L1=__massassign_R0);     // ?{}
702    int __multassign_R2 = (*__massassign_L2=(int)__massassign_R0);   // ?{}
704    // perform construction of statement expr return variable using
705    // RHS value temporary
706    ((*__multassign_L0 = __multassign_R0 /* ?{} */),
707     (*__multassign_L1 = __multassign_R1 /* ?{} */),
708     (*__multassign_L2 = __multassign_R2 /* ?{} */));
709  });
710  _tmp_stmtexpr_ret0;
712({ // tuple destruction - destruct assign expr value
713  int *__massassign_L3 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
714  double *__massassign_L4 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
715  int *__massassign_L5 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
716  ((*__massassign_L3 /* ^?{} */),
717   (*__massassign_L4 /* ^?{} */),
718   (*__massassign_L5 /* ^?{} */));
721A variable is generated to store the value produced by a statement expression, since its fields may need to be constructed with a non-trivial constructor and it may need to be referred to multiple time, e.g., in a unique expression.
722$N$ LHS variables are generated and constructed using the address of the tuple components, and a single RHS variable is generated to store the value of the RHS without any loss of precision.
723A nested statement expression is generated that performs the individual assignments and constructs the return value using the results of the individual assignments.
724Finally, the statement expression temporary is destroyed at the end of the expression.
726Similarly, a multiple assignment
728[x, y, z] = [f(), 3];       // multiple assignment
732// [x, y, z] = [f(), 3];
733_tuple3_(int, double, int) _tmp_stmtexpr_ret0;
735  // assign LHS address temporaries
736  int *__multassign_L0 = &x;    // ?{}
737  double *__multassign_L1 = &y; // ?{}
738  int *__multassign_L2 = &z;    // ?{}
740  // assign RHS value temporaries
741  _tuple2_(double, double) _tmp_cp_ret0;
742  _Bool _unq0_finished_ = 0;
743  double __multassign_R0 =
744    (_unq0_finished_ ?
745      _tmp_cp_ret0 :
746      (_tmp_cp_ret0=f(), _unq0_finished_=1, _tmp_cp_ret0)).0; // ?{}
747  double __multassign_R1 =
748    (_unq0_finished_ ?
749      _tmp_cp_ret0 :
750      (_tmp_cp_ret0=f(), _unq0_finished_=1, _tmp_cp_ret0)).1; // ?{}
751  ({ // tuple destruction - destruct f() return temporary - tuple destruction
752    // assign LHS address temporaries
753    double *__massassign_L3 = (double *)&_tmp_cp_ret0.0;  // ?{}
754    double *__massassign_L4 = (double *)&_tmp_cp_ret0.1;  // ?{}
755    // perform destructions - intrinsic, so NOP
756    ((*__massassign_L3 /* ^?{} */),
757     (*__massassign_L4 /* ^?{} */));
758  });
759  int __multassign_R2 = 3; // ?{}
761  ({ // tuple construction - construct statement expr return variable
762    // assign LHS address temporaries
763    int *__multassign_L3 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
764    double *__multassign_L4 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
765    int *__multassign_L5 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
767    // assign RHS value temporaries and perform multiple assignment to L0, L1, L2
768    int __multassign_R3 = (*__multassign_L0=(int)__multassign_R0);  // ?{}
769    double __multassign_R4 = (*__multassign_L1=__multassign_R1);    // ?{}
770    int __multassign_R5 = (*__multassign_L2=__multassign_R2);       // ?{}
772    // perform construction of statement expr return variable using
773    // RHS value temporaries
774    ((*__multassign_L3=__multassign_R3 /* ?{} */),
775     (*__multassign_L4=__multassign_R4 /* ?{} */),
776     (*__multassign_L5=__multassign_R5 /* ?{} */));
777  });
778  _tmp_stmtexpr_ret0;
780({  // tuple destruction - destruct assign expr value
781  // assign LHS address temporaries
782  int *__massassign_L5 = (int *)&_tmp_stmtexpr_ret0.0;       // ?{}
783  double *__massassign_L6 = (double *)&_tmp_stmtexpr_ret0.1; // ?{}
784  int *__massassign_L7 = (int *)&_tmp_stmtexpr_ret0.2;       // ?{}
785  // perform destructions - intrinsic, so NOP
786  ((*__massassign_L5 /* ^?{} */),
787   (*__massassign_L6 /* ^?{} */),
788   (*__massassign_L7 /* ^?{} */));
791The difference here is that $N$ RHS values are stored into separate temporary variables.
793The use of statement expressions allows the translator to arbitrarily generate additional temporary variables as needed, but binds the implementation to a non-standard extension of the C language.
794There are other places where the \CFA translator makes use of GNU C extensions, such as its use of nested functions, so this is not a new restriction.
Note: See TracBrowser for help on using the repository browser.