[9c2ac95] | 1 | \chapter{Recent Features Introduced to \CFA} |
---|
[2e94f3e7] | 2 | \label{c:content1} |
---|
| 3 | |
---|
[7a37fcb1] | 4 | This chapter discusses some recent additions to the \CFA language and their interactions with the type system. |
---|
[9c2ac95] | 5 | |
---|
| 6 | |
---|
[7a37fcb1] | 7 | \section{Reference Types} |
---|
[9c2ac95] | 8 | |
---|
[7a37fcb1] | 9 | Reference types were added to \CFA by Robert Schluntz and Aaron Moss~\cite{Moss18}. |
---|
| 10 | The \CFA reference type generalizes the \CC reference type (and its equivalent in other modern programming languages) by providing both mutable and immutable forms and cascading referencing and dereferencing. |
---|
| 11 | Specifically, \CFA attempts to extend programmer intuition about pointers to references. |
---|
| 12 | That is, use a pointer when its primary purpose is manipulating the address of storage, \eg a top/head/tail pointer or link field in a mutable data structure. |
---|
| 13 | Here, manipulating the pointer address is the primary operation, while dereferencing the pointer to its value is the secondary operation. |
---|
| 14 | For example, \emph{within} a data structure, \eg stack or queue, all operations involve pointer addresses and the pointer may never be dereferenced because the referenced object is opaque. |
---|
| 15 | Alternatively, use a reference when its primary purpose is to alias a value, \eg a function parameter that does not copy the argument (performance reason). |
---|
| 16 | Here, manipulating the value is the primary operation, while changing the pointer address is the secondary operation. |
---|
| 17 | Succinctly, if the address often changes, use a pointer; |
---|
| 18 | if the value often changes, use a reference. |
---|
| 19 | Note, \CC made the reference address immutable starting a \emph{belief} that immutability is a fundamental aspect of a reference's pointer, resulting in a semantic asymmetry between the pointer and reference. |
---|
| 20 | \CFA adopts a uniform policy between pointers and references where mutability is a settable property at the point of declaration. |
---|
| 21 | |
---|
| 22 | The following examples shows how pointers and references are treated uniformly in \CFA. |
---|
| 23 | \begin{cfa}[numbers=left,numberblanklines=false] |
---|
[9c2ac95] | 24 | int x = 1, y = 2, z = 3; |
---|
[7a37fcb1] | 25 | int * p1 = &x, ** p2 = &p1, *** p3 = &p2, $\C{// pointers to x}$ |
---|
| 26 | @&@ r1 = x, @&&@ r2 = r1, @&&&@ r3 = r2; $\C{// references to x}$ |
---|
[9c2ac95] | 27 | int * p4 = &z, & r4 = z; |
---|
| 28 | |
---|
[7a37fcb1] | 29 | *p1 = 3; **p2 = 3; ***p3 = 3; $\C{// different ways to change x to 3}$ |
---|
| 30 | r1 = 3; r2 = 3; r3 = 3; $\C{// change x: implicit dereference *r1, **r2, ***r3}$ |
---|
| 31 | **p3 = &y; *p3 = &p4; $\C{// change p1, p2}$ |
---|
[9c2ac95] | 32 | // cancel implicit dereferences (&*)**r3, (&(&*)*)*r3, &(&*)r4 |
---|
[7a37fcb1] | 33 | @&@r3 = @&@y; @&&@r3 = @&&@r4; $\C{// change r1, r2}$ |
---|
[9c2ac95] | 34 | \end{cfa} |
---|
[7a37fcb1] | 35 | Like pointers, reference can be cascaded, \ie a reference to a reference, \eg @&& r2@.\footnote{ |
---|
| 36 | \CC uses \lstinline{&&} for rvalue reference a feature for move semantics and handling the \lstinline{const} Hell problem.} |
---|
| 37 | Usage of a reference variable automatically performs the same number of dereferences as the number of references in its declaration, \eg @r3@ becomes @***r3@. |
---|
| 38 | Finally, to reassign a reference's address needs a mechanism to stop the auto-referencing, which is accomplished by using a single reference to cancel all the auto-dereferencing, \eg @&r3 = &y@ resets @r3@'s address to point to @y@. |
---|
| 39 | \CFA's reference type (including multi-de/references) is powerful enough to describe the lvalue rules in C by types only. |
---|
| 40 | As a result, the \CFA type checker now works on just types without using the notion of lvalue in an expression. |
---|
| 41 | (\CFA internals still use lvalue for code generation purposes.) |
---|
| 42 | |
---|
| 43 | The current reference typing rules in \CFA are summarized as follows: |
---|
[9c2ac95] | 44 | \begin{enumerate} |
---|
[7a37fcb1] | 45 | \item For a variable $x$ with declared type $T$, the variable-expression $x$ has type reference to $T$, even if $T$ itself is a reference type. |
---|
| 46 | \item For an expression $e$ with type $T\ \&_1...\&_n$, \ie $T$ followed by $n$ references, where $T$ is not a reference type, the expression $\&T$ (address of $T$) has type $T *$ followed by $n - 1$ references. |
---|
| 47 | \item For an expression $e$ with type $T *\&_1...\&_n$, \ie $T *$ followed by $n$ references, the expression $* T$ (dereference $T$) has type $T$ followed by $n + 1$ references. |
---|
| 48 | This is the reverse of the previous rule, such that address-of and dereference operators are perfect inverses. |
---|
| 49 | \item When matching parameter and argument types in a function call context, the number of references on the argument type is stripped off to match the number of references on the parameter type.\footnote{ |
---|
| 50 | \CFA handles the \lstinline{const} Hell problem by allowing rvalue expressions to be converted to reference values by implicitly creating a temporary variable, with some restrictions.} |
---|
| 51 | In an assignment context, the left-hand-side operand-type is always reduced to a single reference. |
---|
[9c2ac95] | 52 | \end{enumerate} |
---|
[7a37fcb1] | 53 | Under this ruleset, a type parameter is never bound to a reference type in a function-call context. |
---|
[9c2ac95] | 54 | \begin{cfa} |
---|
[7a37fcb1] | 55 | forall( T ) void f( T & ); |
---|
| 56 | int & x; |
---|
| 57 | f( x ); // implicit dereference |
---|
[9c2ac95] | 58 | \end{cfa} |
---|
[7a37fcb1] | 59 | The call applies an implicit dereference once to @x@ so the call is typed @f( int & )@ with @T = int@, rather than with @T = int &@. |
---|
[9c2ac95] | 60 | |
---|
[7a37fcb1] | 61 | As for a pointer type, a reference type may have qualifiers, where @const@ is most interesting. |
---|
| 62 | \begin{cfa} |
---|
| 63 | int x = 3; $\C{// mutable}$ |
---|
| 64 | const int cx = 5; $\C{// immutable}$ |
---|
| 65 | int * const cp = &x, $\C{// immutable pointer}$ |
---|
| 66 | & const cr = cx; |
---|
| 67 | const int * const ccp = &cx, $\C{// immutable value and pointer}$ |
---|
| 68 | & const ccr = cx; |
---|
| 69 | // pointer |
---|
| 70 | *cp = 7; |
---|
| 71 | cp = &x; $\C{// error, assignment of read-only variable}$ |
---|
| 72 | *ccp = 7; $\C{// error, assignment of read-only location}$ |
---|
| 73 | ccp = &cx; $\C{// error, assignment of read-only variable}$ |
---|
| 74 | // reference |
---|
| 75 | cr = 7; |
---|
| 76 | cr = &x; $\C{// error, assignment of read-only variable}$ |
---|
| 77 | *ccr = 7; $\C{// error, assignment of read-only location}$ |
---|
| 78 | ccr = &cx; $\C{// error, assignment of read-only variable}$ |
---|
| 79 | \end{cfa} |
---|
| 80 | Interestingly, C does not give a warning/error if a @const@ pointer is not initialized, while \CC does. |
---|
| 81 | Hence, type @& const@ is similar to \CC reference, but \CFA does not preclude initialization with a non-variable address. |
---|
| 82 | For example, in system's programming, there are cases where an immutable address is initialized to a specific memory location. |
---|
| 83 | \begin{cfa} |
---|
| 84 | int & const mem_map = *0xe45bbc67@p@; $\C{// hardware mapped registers ('p' for pointer)}$ |
---|
| 85 | \end{cfa} |
---|
| 86 | Finally, qualification is generalized across all pointer/reference declarations. |
---|
| 87 | \begin{cfa} |
---|
| 88 | const * const * const * const ccccp = ... |
---|
| 89 | const & const & const & const ccccr = ... |
---|
| 90 | \end{cfa} |
---|
[9c2ac95] | 91 | |
---|
[7a37fcb1] | 92 | In the initial \CFA reference design, the goal was to make the reference type a \emph{real} data type \vs a restricted \CC reference, which is mostly used for choosing the argument-passing method, by-value or by-reference. |
---|
| 93 | However, there is an inherent ambiguity for auto-dereferencing: every argument expression involving a reference variable can potentially mean passing the reference's value or address. |
---|
| 94 | Without any restrictions, this ambiguity limits the behaviour of reference types in \CFA polymorphic functions, where a type @T@ can bind to a reference or non-reference type. |
---|
| 95 | This ambiguity prevents the type system treating reference types the same way as other types in many cases even if type variables could be bound to reference types. |
---|
| 96 | The reason is that \CFA uses a common \emph{object} trait (constructor, destructor and assignment operators) to handle passing dynamic concrete type arguments into polymorphic functions, and the reference types are handled differently in these contexts so they do not satisfy this common interface. |
---|
[9c2ac95] | 97 | |
---|
[7a37fcb1] | 98 | Moreover, there is also some discrepancy in how the reference types are treated in initialization and assignment expressions. |
---|
| 99 | For example, in line 3 of the previous example code: |
---|
| 100 | \begin{cfa} |
---|
| 101 | int @&@ r1 = x, @&&@ r2 = r1, @&&&@ r3 = r2; $\C{// references to x}$ |
---|
| 102 | \end{cfa} |
---|
| 103 | each initialization expression is implicitly dereferenced to match the types, \eg @&x@, because an address is always required and a variable normally returns its value; |
---|
| 104 | \CC does the same implicit dereference when initializing its reference variables. |
---|
| 105 | For lines 6 and 9 of the previous example code: |
---|
| 106 | \begin{cfa} |
---|
| 107 | r1 = 3; r2 = 3; r3 = 3; $\C{// change x: implicit dereference *r1, **r2, ***r3}$ |
---|
| 108 | @&@r3 = @&@y; @&&@r3 = @&&@r4; $\C{// change r1, r2}$ |
---|
| 109 | \end{cfa} |
---|
| 110 | there are no actual assignment operators defined for reference types that can be overloaded; |
---|
| 111 | instead, all reference assignments are handled by semantic actions in the type system. |
---|
| 112 | In fact, the reassignment of reference variables is setup internally to use the assignment operators for pointer types. |
---|
| 113 | Finally, there is an annoying issue (although purely syntactic) for setting a mutable reference to a specific address like null, @int & r1 = *0p@, which looks like dereferencing a null pointer. |
---|
| 114 | Here, the expression is rewritten as @int & r1 = &(*0p)@, like the variable dereference of @x@ above. |
---|
| 115 | However, the implicit @&@ needs to be cancelled for an address, which is done with the @*@, i.e., @&*@ cancel each other, giving @0p@. |
---|
| 116 | Therefore, the dereferencing operation does not actually happen and the expression is translated into directly initializing the reference variable with the address. |
---|
| 117 | Note, the same explicit reference is used in \CC to set a reference variable to null. |
---|
| 118 | \begin{c++} |
---|
| 119 | int & ip = @*@(int *)nullptr; |
---|
| 120 | \end{c++} |
---|
| 121 | which is used in certain systems-programming situations. |
---|
| 122 | |
---|
| 123 | When generic types were introduced to \CFA~\cite{Moss19}, some thought was given to allow reference types as type arguments. |
---|
| 124 | \begin{cfa} |
---|
| 125 | forall( T ) |
---|
| 126 | struct vector { T t; }; |
---|
| 127 | vector( int @&@ ) vec; $\C{// vector of references to ints}$ |
---|
| 128 | \end{cfa} |
---|
| 129 | While it is possible to write a reference type as the argument to a generic type, it is disallowed in assertion checking, if the generic type requires the object trait for the type argument (a fairly common use case). |
---|
| 130 | Even if the object trait can be made optional, the current type system often misbehaves by adding undesirable auto-dereference on the referenced-to value rather than the reference variable itself, as intended. |
---|
| 131 | Some tweaks are necessary to accommodate reference types in polymorphic contexts and it is unclear what can or cannot be achieved. |
---|
| 132 | Currently, there are contexts where \CFA programmer must use pointer types, giving up the benefits of auto-dereference operations and better syntax from reference types. |
---|
[9c2ac95] | 133 | |
---|
| 134 | |
---|
| 135 | \section{Tuple Types} |
---|
| 136 | |
---|
[7a37fcb1] | 137 | The addition of tuple types to \CFA can be traced back to the original design by David Till in \mbox{K-W C}~\cite{Till89,Buhr94a}, a predecessor project of \CFA. |
---|
| 138 | The primary purpose of tuples is to eliminate output parameters or creating an aggregate type to return multiple values from a function, called a multiple-value-returning (MVR) function. |
---|
| 139 | The following examples shows the two techniques for a function returning three values. |
---|
| 140 | \begin{cquote} |
---|
| 141 | \begin{tabular}{@{}l@{\hspace{20pt}}l@{}} |
---|
[9c2ac95] | 142 | \begin{cfa} |
---|
| 143 | |
---|
[7a37fcb1] | 144 | int foo( int &p2, int &p3 ); // in/out parameters |
---|
| 145 | int x, y = 3, z = 4; |
---|
| 146 | x = foo( y, z ); // return 3 values |
---|
[9c2ac95] | 147 | \end{cfa} |
---|
[7a37fcb1] | 148 | & |
---|
[9c2ac95] | 149 | \begin{cfa} |
---|
[7a37fcb1] | 150 | struct Ret { int x, y, z; }; |
---|
| 151 | Ret foo( int p2, int p3 ); // multiple return values |
---|
| 152 | Ret ret = { .y = 3, .z = 4 }; |
---|
| 153 | ret = foo( ret.y, ret.z ); // return 3 values |
---|
[9c2ac95] | 154 | \end{cfa} |
---|
[7a37fcb1] | 155 | \end{tabular} |
---|
| 156 | \end{cquote} |
---|
| 157 | where K-W C allows direct return of multiple values. |
---|
[9c2ac95] | 158 | \begin{cfa} |
---|
[7a37fcb1] | 159 | @[int, int, int]@ foo( int p2, int p3 ); |
---|
| 160 | @[x, y, z]@ = foo( y, z ); // return 3 values into a tuple |
---|
[9c2ac95] | 161 | \end{cfa} |
---|
[7a37fcb1] | 162 | Along with simplifying returning multiple values, tuples can be extended to simplify a number of other common context that normally require multiple statements and/or additional declarations, all of which reduces coding time and errors. |
---|
[9c2ac95] | 163 | \begin{cfa} |
---|
[7a37fcb1] | 164 | [x, y, z] = 3; $\C[2in]{// x = 3; y = 3; z = 3, where types are different}$ |
---|
| 165 | [x, y] = [y, x]; $\C{// int tmp = x; x = y; y = tmp;}$ |
---|
| 166 | void bar( int, int, int ); |
---|
| 167 | @bar@( foo( 3, 4 ) ); $\C{// int t0, t1, t2; [t0, t1, t2] = foo( 3, 4 ); bar( t0, t1, t2 );}$ |
---|
| 168 | x = foo( 3, 4 )@.1@; $\C{// int t0, t1, t2; [t0, t1, t2] = foo( 3, 4 ); x = t1;}\CRT$ |
---|
[9c2ac95] | 169 | \end{cfa} |
---|
[7a37fcb1] | 170 | For the call to @bar@, the three results from @foo@ are \newterm{flattened} into individual arguments. |
---|
| 171 | Flattening is how tuples interact with parameter and subscript lists, and with other tuples, \eg: |
---|
[9c2ac95] | 172 | \begin{cfa} |
---|
[7a37fcb1] | 173 | [ [ x, y ], z, [a, b, c] ] = [2, [3, 4], foo( 3, 4) ] $\C{// structured}$ |
---|
| 174 | [ x, y, z, a, b, c] = [2, 3, 4, foo( 3, 4) ] $\C{// flattened, where foo results are t0, t1, t2}$ |
---|
[9c2ac95] | 175 | \end{cfa} |
---|
| 176 | |
---|
[7a37fcb1] | 177 | Note, the \CFA type-system supports complex composition of tuples and C type conversions using a costing scheme giving lower cost to widening conversions that do not truncate a value. |
---|
[9c2ac95] | 178 | \begin{cfa} |
---|
[7a37fcb1] | 179 | [ int, int ] foo$\(_1\)$( int ); $\C{// overloaded foo functions}$ |
---|
| 180 | [ double ] foo$\(_2\)$( int ); |
---|
| 181 | void bar( int, double, double ); |
---|
| 182 | bar( foo( 3 ), foo( 3 ) ); |
---|
[9c2ac95] | 183 | \end{cfa} |
---|
[7a37fcb1] | 184 | The type resolver only has the tuple return types to resolve the call to @bar@ as the @foo@ parameters are identical, which involves unifying the flattened @foo@ return values with @bar@'s parameter list. |
---|
| 185 | However, no combination of @foo@s is an exact match with @bar@'s parameters; |
---|
| 186 | thus, the resolver applies C conversions to obtain a best match. |
---|
| 187 | The resulting minimal cost expression is @bar( foo@$_1$@( 3 ), foo@$_2$@( 3 ) )@, where the two possible coversions are (@int@, {\color{red}@int@}, @double@) to (@int@, {\color{red}@double@}, @double@) with a safe (widening) conversion from @int@ to @double@ versus ({\color{red}@double@}, {\color{red}@int@}, {\color{red}@int@}) to ({\color{red}@int@}, {\color{red}@double@}, {\color{red}@double@}) with one unsafe (narrowing) conversion from @double@ to @int@ and two safe conversions from @int@ to @double@. |
---|
| 188 | The programming language Go provides a similar but simplier tuple mechanism, as it does not have overloaded functions. |
---|
| 189 | |
---|
| 190 | The K-W C tuples are merely syntactic sugar, as there is no mechanism to define a variable with tuple type. |
---|
| 191 | For the tuple-returning implementation, an implicit @struct@ type is created for the returning tuple and the values are extracted by field access operations. |
---|
| 192 | For the tuple-assignment implementation, the left-hand tuple expression is expanded into assignments of each component, creating temporary variables to avoid unexpected side effects. |
---|
| 193 | For example, a structure is returned from @foo@ and its fields are individually assigned to the left-hand variables, @x@, @y@, @z@. |
---|
| 194 | |
---|
| 195 | In the second implementation of \CFA tuples by Rodolfo Gabriel Esteves~\cite{Esteves04}, a different strategy is taken to handle MVR functions. |
---|
| 196 | The return values are converted to output parameters passed in by pointers. |
---|
| 197 | When the return values of a MVR function are directly used in an assignment expression, the addresses of the left-hand operands can be directly passed into the function; |
---|
| 198 | composition of MVR functions is handled by creating temporaries for the returns. |
---|
| 199 | For example, given a function returning two values: |
---|
[9c2ac95] | 200 | \begin{cfa} |
---|
[7a37fcb1] | 201 | [int, int] gives_two() { int r1, r2; ... return [ r1, r2 ]; } |
---|
| 202 | int x, y; |
---|
| 203 | [x, y] = gives_two(); |
---|
[9c2ac95] | 204 | \end{cfa} |
---|
[7a37fcb1] | 205 | The K-W C implementation translates the program to: |
---|
[9c2ac95] | 206 | \begin{cfa} |
---|
[7a37fcb1] | 207 | struct _tuple2 { int _0; int _1; } |
---|
| 208 | struct _tuple2 gives_two(); |
---|
| 209 | int x, y; |
---|
| 210 | struct _tuple2 _tmp = gives_two(); |
---|
| 211 | x = _tmp._0; y = _tmp._1; |
---|
| 212 | \end{cfa} |
---|
| 213 | While the Rodolfo implementation translates it to: |
---|
| 214 | \begin{cfa} |
---|
| 215 | void gives_two( int * r1, int * r2 ) { ... *r1 = ...; *r2 = ...; return; } |
---|
| 216 | int x, y; |
---|
| 217 | gives_two( &x, &y ); |
---|
[9c2ac95] | 218 | \end{cfa} |
---|
[7a37fcb1] | 219 | and inside the body of the function @gives_two@, the return statement is rewritten as assignments into the passed-in argument addresses. |
---|
| 220 | This implementation looks more concise, and in the case of returning values having nontrivial types (\eg aggregates), this implementation saves unnecessary copying. |
---|
| 221 | For example, |
---|
| 222 | \begin{cfa} |
---|
| 223 | [ x, y ] gives_two(); |
---|
| 224 | int x, y; |
---|
| 225 | [ x, y ] = gives_two(); |
---|
| 226 | \end{cfa} |
---|
| 227 | becomes |
---|
| 228 | \begin{cfa} |
---|
| 229 | void gives_two( int &, int & ); |
---|
| 230 | int x, y; |
---|
| 231 | gives_two( x, y ); |
---|
| 232 | \end{cfa} |
---|
| 233 | eliminiating any copying in or out of the call. |
---|
| 234 | The downside is indirection within @gives_two@ to access values, unless values get hoisted into registers for some period of time, which is common. |
---|
[9c2ac95] | 235 | |
---|
[7a37fcb1] | 236 | Interestingly, in the third implementation of \CFA tuples by Robert Schluntz~\cite[\S~3]{Schluntz17}, the tuple type reverts back to structure based, where it remains in the current version of the cfa-cc translator. |
---|
| 237 | The reason for the reversion was to make tuples become first-class types in \CFA, \ie allow tuple variables. |
---|
| 238 | This extension was possible, because in parallel with Schluntz's work, generic types were being added independently by Moss~\cite{Moss19}, and the tuple variables leveraged the same implementation techniques as the generic variables. |
---|
[9c2ac95] | 239 | |
---|
[7a37fcb1] | 240 | However, after experience gained building the \CFA runtime system, making tuple-types first-class seems to add little benefit. |
---|
| 241 | The main reason is that tuples usages are largely unstructured, |
---|
[9c2ac95] | 242 | \begin{cfa} |
---|
[7a37fcb1] | 243 | [int, int] foo( int, int ); $\C[2in]{// unstructured function}$ |
---|
| 244 | typedef [int, int] Pair; $\C{// tuple type}$ |
---|
| 245 | Pair bar( Pair ); $\C{// structured function}$ |
---|
| 246 | int x = 3, y = 4; |
---|
| 247 | [x, y] = foo( x, y ); $\C{// unstructured call}$ |
---|
| 248 | Pair ret = [3, 4]; $\C{// tuple variable}$ |
---|
| 249 | ret = bar( ret ); $\C{// structured call}\CRT$ |
---|
| 250 | \end{cfa} |
---|
| 251 | Basically, creating the tuple-type @Pair@ is largely equivalent to creating a @struct@ type, and creating more types and names defeats the simplicity that tuples are trying to achieve. |
---|
| 252 | Furthermore, since operator overloading in \CFA is implemented by treating operators as overloadable functions, tuple types are very rarely used in a structured way. |
---|
| 253 | When a tuple-type expression appears in a function call (except assignment expressions, which are handled differently by mass- or multiple-assignment expansions), it is always flattened, and the tuple structure of function parameter is not considered a part of the function signatures. |
---|
| 254 | For example, |
---|
| 255 | \begin{cfa} |
---|
| 256 | void f( int, int ); |
---|
| 257 | void f( [int, int] ); |
---|
| 258 | f( 3, 4 ); // ambiguous call |
---|
| 259 | \end{cfa} |
---|
| 260 | the two prototypes for @foo@ have the same signature (a function taking two @int@s and returning nothing), and therefore invalid overloads. |
---|
| 261 | Note, the ambiguity error occurs at the call rather than at the second declaration of @f@, because it is possible to have multiple equivalent prototype definitions of a function. |
---|
| 262 | Furthermore, ordinary polymorphic type-parameters are not allowed to have tuple types. |
---|
| 263 | \begin{cfa} |
---|
| 264 | forall( T ) T foo( T ); |
---|
| 265 | int x, y, z; |
---|
| 266 | [x, y, z] = foo( [x, y, z] ); // substitute tuple type for T |
---|
| 267 | \end{cfa} |
---|
| 268 | Without this restriction, the expression resolution algorithm can create too many argument-parameter matching options. |
---|
| 269 | For example, with multiple type parameters, |
---|
| 270 | \begin{cfa} |
---|
| 271 | forall( T, U ) void f( T, U ); |
---|
| 272 | f( [1, 2, 3, 4] ); |
---|
| 273 | \end{cfa} |
---|
| 274 | the call to @f@ can be interpreted as @T = [1]@ and @U = [2, 3, 4, 5]@, or @T = [1, 2]@ and @U = [3, 4, 5]@, and so on. |
---|
| 275 | The restriction ensures type checking remains tractable and does not take too long to compute. |
---|
| 276 | Therefore, tuple types are never present in any fixed-argument function calls. |
---|
| 277 | |
---|
| 278 | Finally, a type-safe variadic argument signature was added by Robert Schluntz~\cite[\S~4.1.2]{Schluntz17} using @forall@ and a new tuple parameter-type, denoted by the keyword @ttype @ in Schluntz's implementation, but changed to the ellipsis syntax similar to \CC's template parameter pack. |
---|
| 279 | For C variadics, the number and types of the arguments must be conveyed in some way, \eg @printf@ uses a format string indicating the number and types of the arguments. |
---|
| 280 | \VRef[Figure]{f:CVariadicMaxFunction} shows an $N$ argument @maxd@ function using the C untyped @va_list@ interface. |
---|
| 281 | In the example, the first argument is the number of following arguments, and the following arguments are assumed to be @double@; |
---|
| 282 | looping is used to traverse the argument pack from left to right. |
---|
| 283 | The @va_list@ interface is walking up (by address) the stack looking at the arguments pushed by the caller. |
---|
| 284 | (Magic knowledge is needed for arguments pushed using registers.) |
---|
| 285 | |
---|
| 286 | \begin{figure} |
---|
| 287 | \begin{cfa} |
---|
| 288 | double maxd( int @count@, ... ) { |
---|
| 289 | double max = 0; |
---|
| 290 | va_list args; |
---|
| 291 | va_start( args, count ); |
---|
| 292 | for ( int i = 0; i < count; i += 1 ) { |
---|
| 293 | double num = va_arg( args, double ); |
---|
| 294 | if ( num > max ) max = num; |
---|
[9c2ac95] | 295 | } |
---|
[7a37fcb1] | 296 | va_end(args); |
---|
| 297 | return max; |
---|
| 298 | } |
---|
| 299 | printf( "%g\n", maxd( @4@, 25.0, 27.3, 26.9, 25.7 ) ); |
---|
[9c2ac95] | 300 | \end{cfa} |
---|
[7a37fcb1] | 301 | \caption{C Variadic Maximum Function} |
---|
| 302 | \label{f:CVariadicMaxFunction} |
---|
| 303 | \end{figure} |
---|
| 304 | |
---|
| 305 | There are two common patterns for using the variadic functions in \CFA. |
---|
| 306 | \begin{enumerate}[leftmargin=*] |
---|
| 307 | \item |
---|
| 308 | Argument forwarding to another function, \eg: |
---|
[9c2ac95] | 309 | \begin{cfa} |
---|
[7a37fcb1] | 310 | forall( T *, TT ... | { @void ?{}( T &, TT );@ } ) // constructor assertion |
---|
| 311 | T * new( TT tp ) { return ((T *)malloc())@{@ tp @}@; } // call constructor on storage |
---|
[9c2ac95] | 312 | \end{cfa} |
---|
[7a37fcb1] | 313 | Note, the assertion on @T@ requires it to have a constructor @?{}@. |
---|
| 314 | The function @new@ calls @malloc@ to obtain storage and then invokes @T@'s constructor passing the tuple pack by flattening it over the constructor's arguments, \eg: |
---|
[9c2ac95] | 315 | \begin{cfa} |
---|
[7a37fcb1] | 316 | struct S { int i, j; }; |
---|
| 317 | void ?{}( S & s, int i, int j ) { s.[ i, j ] = [ i, j ]; } // constructor |
---|
| 318 | S * sp = new( 3, 4 ); // flatten [3, 4] into call ?{}( 3, 4 ); |
---|
[9c2ac95] | 319 | \end{cfa} |
---|
[7a37fcb1] | 320 | \item |
---|
| 321 | Structural recursion for processing the argument-pack values one at a time, \eg: |
---|
[9c2ac95] | 322 | \begin{cfa} |
---|
[7a37fcb1] | 323 | forall( T | { int ?>?( T, T ); } ) |
---|
| 324 | T max( T v1, T v2 ) { return v1 > v2 ? v1 : v2; } |
---|
| 325 | $\vspace{-10pt}$ |
---|
| 326 | forall( T, TT ... | { T max( T, T ); T max( TT ); } ) |
---|
| 327 | T max( T arg, TT args ) { return max( arg, max( args ) ); } |
---|
[9c2ac95] | 328 | \end{cfa} |
---|
[7a37fcb1] | 329 | The first non-recursive @max@ function is the polymorphic base-case for the recursion, \ie, find the maximum of two identically typed values with a greater-than (@>@) operator. |
---|
| 330 | The second recursive @max@ function takes two parameters, a @T@ and a @TT@ tuple pack, handling all argument lengths greater than two. |
---|
| 331 | The recursive function computes the maximum for the first argument and the maximum value of the rest of the tuple pack. |
---|
| 332 | The call of @max@ with one argument is the recursive call, where the tuple pack is converted into two arguments by taking the first value (lisp @car@) from the tuple pack as the first argument (flattening) and the remaining pack becomes the second argument (lisp @cdr@). |
---|
| 333 | The recursion stops when the argument pack is empty. |
---|
| 334 | For example, @max( 2, 3, 4 )@ matches with the recursive function, which performs @return max( 2, max( [3, 4] ) )@ and one more step yields @return max( 2, max( 3, 4 ) )@, so the tuple pack is empty. |
---|
| 335 | \end{enumerate} |
---|
[9c2ac95] | 336 | |
---|
[7a37fcb1] | 337 | As an aside, polymorphic functions are precise with respect to their parameter types, \eg @max@ states all argument values must be the same type, which logically makes sense. |
---|
| 338 | However, this precision precludes normal C conversions among the base types, \eg, this mix-mode call @max( 2h, 2l, 3.0f, 3.0ld )@ fails because the types are not the same. |
---|
| 339 | Unfortunately, this failure violates programmer intuition because there are specialized two-argument non-polymorphic versions of @max@ that work, \eg @max( 3, 3.5 )@. |
---|
| 340 | Allowing C conversions for polymorphic types will require a significant change to the type resolver. |
---|
| 341 | |
---|
| 342 | Currently in \CFA, variadic polymorphic functions are the only place tuple types are used. |
---|
| 343 | And because \CFA compiles polymorphic functions versus template expansion, many wrapper functions are generated to implement both user-defined generic-types and polymorphism with variadics. |
---|
| 344 | Fortunately, the only permitted operations on polymorphic function parameters are given by the list of assertion (trait) functions. |
---|
| 345 | Nevertheless, this small set of functions eventually need to be called with flattened tuple arguments. |
---|
| 346 | Unfortunately, packing the variadic arguments into a rigid @struct@ type and generating all the required wrapper functions is significant work and largely wasted because most are never called. |
---|
| 347 | Interested readers can refer to pages 77-80 of Robert Schluntz's thesis to see how verbose the translator output is to implement a simple variadic call with 3 arguments. |
---|
| 348 | As the number of arguments increases, \eg a call with 5 arguments, the translator generates a concrete @struct@ types for a 4-tuple and a 3-tuple along with all the polymorphic type data for them. |
---|
| 349 | An alternative approach is to put the variadic arguments into an array, along with an offset array to retrieve each individual argument. |
---|
| 350 | This method is similar to how the C @va_list@ object is used (and how \CFA accesses polymorphic fields in a generic type), but the \CFA variadics generate the required type information to guarantee type safety. |
---|
| 351 | For example, given the following heterogeneous, variadic, typed @print@ and usage. |
---|
| 352 | \begin{cquote} |
---|
| 353 | \begin{tabular}{@{}ll@{}} |
---|
| 354 | \begin{cfa} |
---|
| 355 | forall( T, TT ... | { void print( T ); void print( TT ); } ) |
---|
| 356 | void print( T arg , TT rest ) { |
---|
| 357 | print( arg ); |
---|
| 358 | print( rest ); |
---|
| 359 | } |
---|
| 360 | \end{cfa} |
---|
| 361 | & |
---|
| 362 | \begin{cfa} |
---|
| 363 | void print( int i ) { printf( "%d ", i ); } |
---|
| 364 | void print( double d ) { printf( "%g ", d ); } |
---|
| 365 | ... // other types |
---|
| 366 | int i = 3 ; double d = 3.5; |
---|
| 367 | print( i, d ); |
---|
| 368 | \end{cfa} |
---|
| 369 | \end{tabular} |
---|
| 370 | \end{cquote} |
---|
| 371 | it would look like the following using the offset-array implementation approach. |
---|
| 372 | \begin{cfa} |
---|
| 373 | void print( T arg, char * _data_rest, size_t * _offset_rest ) { |
---|
| 374 | print( arg ); |
---|
| 375 | print( *((typeof rest.0)*) _data_rest, $\C{// first element of rest}$ |
---|
| 376 | _data_rest + _offset_rest[0], $\C{// remainder of data}$ |
---|
| 377 | _offset_rest + 1); $\C{// remainder of offset array}$ |
---|
| 378 | } |
---|
| 379 | \end{cfa} |
---|
| 380 | where the fixed-arg polymorphism for @T@ can be handled by the standard @void *@-based \CFA polymorphic calling conventions, and the type information can all be deduced at the call site. |
---|
| 381 | Note, the variadic @print@ supports heterogeneous types because the polymorphic @T@ is not returned (unlike variadic @max@), so there is no cascade of type relationships. |
---|
| 382 | |
---|
| 383 | Turning tuples into first-class values in \CFA does have a few benefits, namely allowing pointers to tuples and arrays of tuples to exist. |
---|
| 384 | However, it seems unlikely that these types have realistic use cases that cannot be achieved without them. |
---|
| 385 | And having a pointer-to-tuple type potentially forbids the simple offset-array implementation of variadic polymorphism. |
---|
| 386 | For example, in the case where a type assertion requests the pointer type @TT *@ in the above example, it forces the tuple type to be a @struct@, and thus incurring a high cost. |
---|
| 387 | My conclusion is that tuples should not be structured (first-class), rather they should be unstructured. |
---|
| 388 | This agrees with Rodolfo's original describes |
---|
| 389 | \begin{quote} |
---|
| 390 | As such, their [tuples] use does not enforce a particular memory layout, and in particular, does not guarantee that the components of a tuple occupy a contiguous region of memory.~\cite[pp.~74--75]{Esteves04} |
---|
| 391 | \end{quote} |
---|
| 392 | allowing the simplified implementations for MVR and variadic functions. |
---|
| 393 | |
---|
| 394 | Finally, a missing feature for tuples is using an MVR in an initialization context. |
---|
| 395 | Currently, this feature is \emph{only} possible when declaring a tuple variable. |
---|
| 396 | \begin{cfa} |
---|
| 397 | [int, int] ret = gives_two(); $\C{// no constructor call (unstructured)}$ |
---|
| 398 | Pair ret = gives_two(); $\C{// constructor call (structured)}$ |
---|
| 399 | \end{cfa} |
---|
| 400 | However, this forces the programer to use a tuple variable and possibly a tuple type to support a constructor, when they actually want separate variables with separate constructors. |
---|
| 401 | And as stated previously, type variables (structured tuples) are rare in general \CFA programming so far. |
---|
| 402 | To address this issue, while retaining the ability to leverage constructors, the following new tuple-like declaration syntax is proposed. |
---|
| 403 | \begin{cfa} |
---|
| 404 | [ int x, int y ] = gives_two(); |
---|
| 405 | \end{cfa} |
---|
| 406 | where the semantics is: |
---|
| 407 | \begin{cfa} |
---|
| 408 | T t0, t1; |
---|
| 409 | [ t0, t1 ] = gives_two(); |
---|
| 410 | T x = t0; // constructor call |
---|
| 411 | T y = t1; // constructor call |
---|
| 412 | \end{cfa} |
---|
| 413 | and the implementation performs as much copy elision as possible. |
---|
[9c2ac95] | 414 | |
---|
| 415 | |
---|
[7a37fcb1] | 416 | \section{\lstinline{inline} Substructure} |
---|
[9c2ac95] | 417 | |
---|
[7a37fcb1] | 418 | C allows an anonymous aggregate type (@struct@ or @union@) to be embedded (nested) within another one, \eg a tagged union. |
---|
| 419 | \begin{cfa} |
---|
| 420 | struct S { |
---|
| 421 | unsigned int tag; |
---|
| 422 | union { $\C{// anonymous nested aggregate}$ |
---|
| 423 | int x; double y; char z; |
---|
| 424 | }; |
---|
| 425 | } s; |
---|
| 426 | \end{cfa} |
---|
| 427 | The @union@ field-names are hoisted into the @struct@, so there is direct access, \eg @s.x@; |
---|
| 428 | hence, field names must be unique. |
---|
| 429 | For a nested anonymous @struct@, both field names and values are hoisted. |
---|
| 430 | \begin{cquote} |
---|
| 431 | \begin{tabular}{@{}l@{\hspace{35pt}}l@{}} |
---|
| 432 | original & rewritten \\ |
---|
| 433 | \begin{cfa} |
---|
| 434 | struct S { |
---|
| 435 | struct { int i, j; }; |
---|
| 436 | struct { int k, l; }; |
---|
| 437 | }; |
---|
| 438 | \end{cfa} |
---|
| 439 | & |
---|
| 440 | \begin{cfa} |
---|
| 441 | struct S { |
---|
| 442 | int i, j; |
---|
| 443 | int k, l; |
---|
| 444 | }; |
---|
| 445 | \end{cfa} |
---|
| 446 | \end{tabular} |
---|
| 447 | \end{cquote} |
---|
| 448 | |
---|
| 449 | As an aside, C nested \emph{named} aggregates behave in a (mysterious) way because the nesting is allowed but there is no ability to use qualification to access an inner type, like the \CC type operator `@::@'. |
---|
| 450 | In fact, all named nested aggregates are hoisted to global scope, regardless of the nesting depth. |
---|
| 451 | \begin{cquote} |
---|
| 452 | \begin{tabular}{@{}l@{\hspace{35pt}}l@{}} |
---|
| 453 | original & rewritten \\ |
---|
| 454 | \begin{cfa} |
---|
| 455 | struct S { |
---|
| 456 | struct T { |
---|
| 457 | int i, j; |
---|
| 458 | }; |
---|
| 459 | struct U { |
---|
| 460 | int k, l; |
---|
| 461 | }; |
---|
| 462 | }; |
---|
| 463 | \end{cfa} |
---|
| 464 | & |
---|
[9c2ac95] | 465 | \begin{cfa} |
---|
| 466 | struct T { |
---|
[7a37fcb1] | 467 | int i, j; |
---|
| 468 | }; |
---|
| 469 | struct U { |
---|
| 470 | int k, l; |
---|
| 471 | }; |
---|
| 472 | struct S { |
---|
| 473 | }; |
---|
[9c2ac95] | 474 | \end{cfa} |
---|
[7a37fcb1] | 475 | \end{tabular} |
---|
| 476 | \end{cquote} |
---|
| 477 | Hence, the possible accesses are: |
---|
[9c2ac95] | 478 | \begin{cfa} |
---|
[7a37fcb1] | 479 | struct S s; // s cannot access any fields |
---|
| 480 | struct T t; t.i; t.j; |
---|
| 481 | struct U u; u.k; u.l; |
---|
[9c2ac95] | 482 | \end{cfa} |
---|
[7a37fcb1] | 483 | and the hoisted type names can clash with global types names. |
---|
| 484 | For good reasons, \CC chose to change this semantics~\cite[C.1.2.3.3]{C++}: |
---|
| 485 | \begin{description}[leftmargin=*,topsep=3pt,itemsep=0pt,parsep=0pt] |
---|
| 486 | \item[Change:] A struct is a scope in C++, not in C. |
---|
| 487 | \item[Rationale:] Class scope is crucial to C++, and a struct is a class. |
---|
| 488 | \item[Effect on original feature:] Change to semantics of well-defined feature. |
---|
| 489 | \item[Difficulty of converting:] Semantic transformation. |
---|
| 490 | \item[How widely used:] C programs use @struct@ extremely frequently, but the change is only noticeable when @struct@, enumeration, or enumerator names are referred to outside the @struct@. |
---|
| 491 | The latter is probably rare. |
---|
| 492 | \end{description} |
---|
| 493 | However, there is no syntax to access from a variable through a type to a field. |
---|
[9c2ac95] | 494 | \begin{cfa} |
---|
[7a37fcb1] | 495 | struct S s; @s::T@.i; @s::U@.k; |
---|
| 496 | \end{cfa} |
---|
[9c2ac95] | 497 | |
---|
[7a37fcb1] | 498 | As an aside, \CFA also provides a backwards compatible \CC nested-type. |
---|
| 499 | \begin{cfa} |
---|
| 500 | struct S { |
---|
| 501 | @auto@ struct T { |
---|
| 502 | int i, j; |
---|
| 503 | }; |
---|
| 504 | @auto@ struct U { |
---|
| 505 | int k, l; |
---|
| 506 | }; |
---|
| 507 | }; |
---|
[9c2ac95] | 508 | \end{cfa} |
---|
[7a37fcb1] | 509 | The keyword @auto@ denotes a local (scoped) declaration, and here, it implies a local (scoped) type, using dot as the type qualifier, \eg @S.T t@. |
---|
[075c6d5] | 510 | Alternatively, \CFA could adopt the \CC non-compatible change for nested types, since it may have already forced certain coding changes in C libraries that must be parsed by \CC. |
---|
[9c2ac95] | 511 | |
---|
[7a37fcb1] | 512 | % https://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html |
---|
[9c2ac95] | 513 | |
---|
[7a37fcb1] | 514 | A polymorphic extension to nested aggregates appears in the Plan-9 C dialect, used in the Bell Labs' Plan-9 research operating system. |
---|
| 515 | The feature is called \newterm{unnamed substructures}~\cite[\S~3.3]{Thompson90new}, which continues to be supported by @gcc@ and @clang@ using the extension (@-fplan9-extensions@). |
---|
| 516 | The goal is to provided the same effect of the nested aggregate with the aggregate type defined elsewhere, which requires it be named. |
---|
| 517 | \begin{cfa} |
---|
| 518 | union U { $\C{// unnested named}$ |
---|
| 519 | int x; double y; char z; |
---|
| 520 | } u; |
---|
| 521 | struct W { |
---|
| 522 | int i; double j; char k; |
---|
| 523 | } w; |
---|
| 524 | struct S { |
---|
| 525 | @struct W;@ $\C{// Plan-9 substructure}$ |
---|
| 526 | unsigned int tag; |
---|
| 527 | @union U;@ $\C{// Plan-9 substructure}$ |
---|
| 528 | } s; |
---|
| 529 | \end{cfa} |
---|
| 530 | Note, the position of the substructure is normally unimportant. |
---|
| 531 | Like the anonymous nested types, the aggregate field names are hoisted into @struct S@, so there is direct access, \eg @s.x@ and @s.i@. |
---|
| 532 | However, like the implicit C hoisting of nested structures, the field names must be unique and the type names are now at a different scope level, unlike type nesting in \CC. |
---|
| 533 | In addition, a pointer to a structure is automatically converted to a pointer to an anonymous field for assignments and function calls, providing containment inheritance with implicit subtyping, \ie @U@ $\subset$ @S@ and @W@ $\subset$ @S@. |
---|
| 534 | For example: |
---|
| 535 | \begin{cfa} |
---|
| 536 | void f( union U * u ); |
---|
| 537 | void g( struct W * ); |
---|
| 538 | union U * up; |
---|
| 539 | struct W * wp; |
---|
| 540 | struct S * sp; |
---|
| 541 | up = sp; $\C{// assign pointer to U in S}$ |
---|
| 542 | wp = sp; $\C{// assign pointer to W in S}$ |
---|
| 543 | f( &s ); $\C{// pass pointer to U in S}$ |
---|
| 544 | g( &s ); $\C{// pass pointer to W in S}$ |
---|
| 545 | \end{cfa} |
---|
[9c2ac95] | 546 | |
---|
[7a37fcb1] | 547 | \CFA extends the Plan-9 substructure by allowing polymorphism for values and pointers. |
---|
| 548 | The extended substructure is denoted using @inline@, allowing backwards compatibility to existing Plan-9 features. |
---|
| 549 | \begin{cfa} |
---|
| 550 | struct S { |
---|
| 551 | @inline@ W; $\C{// extended Plan-9 substructure}$ |
---|
| 552 | unsigned int tag; |
---|
| 553 | @inline@ U; $\C{// extended Plan-9 substructure}$ |
---|
| 554 | } s; |
---|
| 555 | \end{cfa} |
---|
| 556 | Note, like \CC, \CFA allows optional prefixing of type names with their kind, \eg @struct@, @union@, and @enum@, unless there is ambiguity with variable names in the same scope. |
---|
| 557 | The following shows both value and pointer polymorphism. |
---|
| 558 | \begin{cfa} |
---|
| 559 | void f( U, U * ); $\C{// value, pointer}$ |
---|
| 560 | void g( W, W * ); $\C{// value, pointer}$ |
---|
| 561 | U u, * up; |
---|
| 562 | S s, * sp; |
---|
| 563 | W w, * wp; |
---|
| 564 | u = s; up = sp; $\C{// value, pointer}$ |
---|
| 565 | w = s; wp = sp; $\C{// value, pointer}$ |
---|
| 566 | f( s, &s ); $\C{// value, pointer}$ |
---|
| 567 | g( s, &s ); $\C{// value, pointer}$ |
---|
| 568 | \end{cfa} |
---|
[2e94f3e7] | 569 | |
---|
[7a37fcb1] | 570 | In general, non-standard C features (@gcc@) do not need any special treatment, as they are directly passed through to the C compiler. |
---|
| 571 | However, the Plan-9 semantics allow implicit conversions from the outer type to the inner type, which means the \CFA type resolver must take this information into account. |
---|
| 572 | Therefore, the \CFA translator must implement the Plan-9 features and insert necessary type conversions into the translated code output. |
---|
| 573 | In the current version of \CFA, this is the only kind of implicit type conversion other than the standard C conversions. |
---|
[2e94f3e7] | 574 | |
---|
[7a37fcb1] | 575 | Since variable overloading is possible in \CFA, \CFA's implementation of Plan-9 polymorphism allows duplicate field names. |
---|
| 576 | When an outer field and an embedded field have the same name and type, the inner field is shadowed and cannot be accessed directly by name. |
---|
| 577 | While such definitions are allowed, duplicate field names is not good practice in general and should be avoided if possible. |
---|
| 578 | Plan-9 fields can be nested, and a struct definition can contain multiple Plan-9 embedded fields. |
---|
| 579 | In particular, the \newterm{diamond pattern}~\cite[\S~6.1]{Stroustrup89}\cite[\S~4]{Cargill91} can occur and result in a nested field to be embedded twice. |
---|
| 580 | \begin{cfa} |
---|
| 581 | struct A { int x; }; |
---|
| 582 | struct B { inline A; }; |
---|
| 583 | struct C { inline A; }; |
---|
| 584 | struct D { |
---|
| 585 | inline B; |
---|
| 586 | inline C; |
---|
| 587 | }; |
---|
| 588 | D d; |
---|
| 589 | \end{cfa} |
---|
| 590 | In the above example, the expression @d.x@ becomes ambiguous, since it can refer to the indirectly embedded field either from @B@ or from @C@. |
---|
| 591 | It is still possible to disambiguate the expression by first casting the outer struct to one of the directly embedded type, such as @((B)d).x@. |
---|