Changeset 7f617cf0 for doc

Aug 6, 2017, 9:02:56 AM (7 years ago)
Peter A. Buhr <pabuhr@…>
ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc

add DRAFT watermark, share new keyword-list, many text changes and movement

1 edited


  • doc/user/user.tex

    r83e680d r7f617cf0  
    1111%% Created On       : Wed Apr  6 14:53:29 2016
    1212%% Last Modified By : Peter A. Buhr
    13 %% Last Modified On : Sat Jul 22 11:01:19 2017
    14 %% Update Count     : 2878
     13%% Last Modified On : Sun Aug  6 08:52:34 2017
     14%% Update Count     : 3034
    3737\usepackage{mathptmx}                                   % better math font with "times"
    39 \usepackage[pagewise]{lineno}
    40 \renewcommand{\linenumberfont}{\scriptsize\sffamily}
    4139\input{common}                                          % common CFA document macros
    4649% Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore
    4750% removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR
    49 \renewcommand{\_}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}}
    5759\CFAStyle                                                                                               % use default CFA format-style
    59 \lstnewenvironment{C++}[1][]
     60\lstnewenvironment{C++}[1][]                            % use C++ style
     81\newcommand{\KWC}{K-W C\xspace}
    107 DRAFT \\ \today
    108110}% date
    197199This document is a programmer reference-manual for the \CFA programming language.
    198200The manual covers the core features of the language and runtime-system, with simple examples illustrating syntax and semantics of each feature.
    199 The manual does not teach programming, i.e., how to combine the new constructs to build complex programs.
     201The manual does not teach programming, \ie how to combine the new constructs to build complex programs.
    200202A reader should already have an intermediate knowledge of control flow, data structures, and concurrency issues to understand the ideas presented, as well as some experience programming in C/\CC.
    201203Implementers should refer to the \CFA Programming Language Specification for details about the language syntax and semantics.
    249 The \CFA project started with \Index*{K-W C}~\cite{Buhr94a,Till89}, which extended C with new declaration syntax, multiple return values from routines, and advanced assignment capabilities using the notion of tuples.
     251The \CFA project started with \Index*{Dave Till}\index{Till, Dave}'s \Index*{K-W C}~\cite{Buhr94a,Till89}, which extended C with new declaration syntax, multiple return values from routines, and advanced assignment capabilities using the notion of tuples.
    250252(See~\cite{Werther96} for similar work in \Index*[C++]{\CC{}}.)
    251 The first \CFA implementation of these extensions was by Esteves~\cite{Esteves04}.
     253The first \CFA implementation of these extensions was by \Index*{Rodolfo Esteves}\index{Esteves, Rodolfo}~\cite{Esteves04}.
    253255The signature feature of \CFA is \emph{\Index{overload}able} \Index{parametric-polymorphic} functions~\cite{forceone:impl,Cormack90,Duggan96} with functions generalized using a ©forall© clause (giving the language its name):
    258260% extending the C type system with parametric polymorphism and overloading, as opposed to the \Index*[C++]{\CC{}} approach of object-oriented extensions.
    259 \CFA{}\hspace{1pt}'s polymorphism was originally formalized by Ditchfield~\cite{Ditchfield92}, and first implemented by Bilson~\cite{Bilson03}.
     261\CFA{}\hspace{1pt}'s polymorphism was originally formalized by \Index*{Glen Ditchfield}\index{Ditchfield, Glen}~\cite{Ditchfield92}, and first implemented by \Index*{Richard Bilson}\index{Bilson, Richard}~\cite{Bilson03}.
    260262However, at that time, there was little interesting in extending C, so work did not continue.
    261263As the saying goes, ``\Index*{What goes around, comes around.}'', and there is now renewed interest in the C programming language because of legacy code-bases, so the \CFA project has been restarted.
    344346The command ©cfa© is used to compile a \CFA program and is based on the \Index{GNU} \Indexc{gcc} command, \eg:
    346 cfa§\indexc{cfa}\index{compilation!cfa@©cfa©}§ [ gcc-options ] C/§\CFA{}§-files [ assembler/loader-files ]
     348cfa§\indexc{cfa}\index{compilation!cfa@©cfa©}§ [ gcc-options ] [ C/§\CFA{}§ source-files ] [ assembler/loader files ]
    348350\CFA programs having the following ©gcc© flags turned on:
    509511For both ©continue© and ©break©, the target label must be directly associated with a ©for©, ©while© or ©do© statement;
    510512for ©break©, the target label can also be associated with a ©switch©, ©if© or compound (©{}©) statement.
    511 \VRef[Figure]{f:MultiLevelResumeTermination} shows the labelled ©continue© and ©break©, specifying which control structure is the target for exit, and the corresponding C program using only ©goto©.
    512 The innermost loop has 7 exit points, which cause resumption or termination of one or more of the 7 \Index{nested control-structure}s.
     513\VRef[Figure]{f:MultiLevelExit} shows ©continue© and ©break© indicating the specific control structure, and the corresponding C program using only ©goto© and labels.
     514The innermost loop has 7 exit points, which cause continuation or termination of one or more of the 7 \Index{nested control-structure}s.
    515 \begin{tabular}{@{\hspace{\parindentlnth}}l@{\hspace{1.5em}}l@{}}
    516 \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{\CFA}}      & \multicolumn{1}{c}{\textbf{C}}        \\
     518\multicolumn{1}{@{\hspace{\parindentlnth}}c@{\hspace{\parindentlnth}}}{\textbf{\CFA}}   & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
    518520®LC:® {
    523525                        ®LF:® for ( ... ) {
    524526                                ®LW:® while ( ... ) {
    525                                         ... break ®LC®; ...             // terminate compound
    526                                         ... break ®LS®; ...             // terminate switch
    527                                         ... break ®LIF®; ...    // terminate if
    528                                         ... continue ®LF;® ...  // resume loop
    529                                         ... break ®LF®; ...             // terminate loop
    530                                         ... continue ®LW®; ...  // resume loop
    531                                         ... break ®LW®; ...             // terminate loop
     527                                        ... break ®LC®; ...
     528                                        ... break ®LS®; ...
     529                                        ... break ®LIF®; ...
     530                                        ... continue ®LF;® ...
     531                                        ... break ®LF®; ...
     532                                        ... continue ®LW®; ...
     533                                        ... break ®LW®; ...
    532534                                } // while
    533535                        } // for
    534536                } else {
    535                         ... break ®LIF®; ...                    // terminate if
     537                        ... break ®LIF®; ...
    536538                } // if
    537539        } // switch
    562564} ®LC:® ;
     575// terminate compound
     576// terminate switch
     577// terminate if
     578// continue loop
     579// terminate loop
     580// continue loop
     581// terminate loop
     585// terminate if
    565 \caption{Multi-level Resume/Termination}
    566 \label{f:MultiLevelResumeTermination}
     591\caption{Multi-level Exit}
    569 \begin{comment}
    570 int main() {
    571   LC: {
    572           LS: switch ( 1 ) {
    573                   case 3:
    574                   LIF: if ( 1 ) {
    575                           LF: for ( ;; ) {
    576                                   LW: while ( 1 ) {
    577                                                 break LC;               // terminate compound
    578                                                 break LS;               // terminate switch
    579                                                 break LIF;              // terminate if
    580                                                 continue LF;    // resume loop
    581                                                 break LF;               // terminate loop
    582                                                 continue LW;    // resume loop
    583                                                 break LW;               // terminate loop
    584                                         } // while
    585                                 } // for
    586                         } else {
    587                                 break LIF;                               // terminate if
    588                         } // if
    589                 } // switch
    590         } // compound
    591         {
    592                 switch ( 1 ) {
    593                   case 3:
    594                         if ( 1 ) {
    595                                 for ( ;; ) {
    596                                         while ( 1 ) {
    597                                                 goto LCx;
    598                                                 goto LSx;
    599                                                 goto LIF;
    600                                                 goto LFC;
    601                                                 goto LFB;
    602                                                 goto LWC;
    603                                                 goto LWB;
    604                                           LWC: ; } LWB: ;
    605                                   LFC: ; } LFB: ;
    606                         } else {
    607                                 goto LIF;
    608                         } L3: ;
    609                 } LSx: ;
    610         } LCx: ;
    611 }
    613 // Local Variables: //
    614 // tab-width: 4 //
    615 // End: //
    616 \end{comment}
    619595Both labelled ©continue© and ©break© are a ©goto©\index{goto@\lstinline $goto$!restricted} restricted in the following ways:
    920896class C {
    921897        int i, j;
    922         int mem() {              ®// implicit "this" parameter
    923 ®               i = 1;          ®// this->i
    924 ®               j = 3;          ®// this->j
    925 ®       }
     898        int mem() {                                     §\C{\color{red}// implicit "this" parameter}§
     899                i = 1;                                  §\C{\color{red}// this->i}§
     900                j = 2;                                  §\C{\color{red}// this->j}§
     901        }
    930906struct S { int i, j; };
    931 int mem( S &this ) {    // explicit "this" parameter
    932         ®this.®i = 1;                     // "this" is not elided
     907int mem( S &®this® ) {                  §\C{// explicit "this" parameter}§
     908        ®this.®i = 1;                           §\C{// "this" is not elided}§
    933909        ®this.®j = 2;
    938914\CFA provides a ©with© clause/statement (see Pascal~\cite[\S~4.F]{Pascal}) to elided the "©this.©" by opening a scope containing field identifiers, changing the qualified fields into variables and giving an opportunity for optimizing qualified references.
    940 int mem( S &this ) ®with this® {        // with clause
    941         i = 1;                  ®// this.i
    942 ®       j = 2;                  ®// this.j
    943 ®}
     916int mem( S &this ) ®with this® { §\C{// with clause}§
     917        i = 1;                                          §\C{\color{red}// this->i}§
     918        j = 2;                                          §\C{\color{red}// this->j}§
    945921which extends to multiple routine parameters:
    992968Exception handling provides two mechanism: change of control flow from a raise to a handler, and communication from the raise to the handler.
    993969Transfer of control can be local, within a routine, or non-local, among routines.
    994 Non-local transfer can cause stack unwinding, i.e., non-local routine termination, depending on the kind of raise.
     970Non-local transfer can cause stack unwinding, \ie non-local routine termination, depending on the kind of raise.
    996972exception_t E {};                               §\C{// exception type}§
    1001977try {
    1002978        f(...);
    1003 } catch( E e : §boolean-predicate§ ) {                  §\C{// termination handler}§
     979} catch( E e : §boolean-predicate§ ) {                  §\C[8cm]{// termination handler}§
    1004980        // recover and continue
    1005 } catchResume( E e : §boolean-predicate§ ) {    §\C{// resumption handler}§
     981} catchResume( E e : §boolean-predicate§ ) {    §\C{// resumption handler}\CRT§
    1006982        // repair and return
    1007983} finally {
    12311207As for \Index{division}, there are exponentiation operators for integral and floating-point types, including the builtin \Index{complex} types.
    1232 Unsigned integral exponentiation\index{exponentiation!unsigned integral} is performed with repeated multiplication (or shifting if the base is 2).
    1233 Signed integral exponentiation\index{exponentiation!signed integral} is performed with repeated multiplication (or shifting if the base is 2), but yields a floating-point result because $b^{-e}=1/b^e$.
     1208Unsigned integral exponentiation\index{exponentiation!unsigned integral} is performed with repeated multiplication\footnote{The multiplication computation is optimized to $O(\log y)$.} (or shifting if the base is 2).
     1209Signed integral exponentiation\index{exponentiation!signed integral} is performed with repeated multiplication (or shifting if the base is 2), but yields a floating-point result because $x^{-y}=1/x^y$.
    12341210Hence, it is important to designate exponent integral-constants as unsigned or signed: ©3 \ 3u© return an integral result, while ©3 \ 3© returns a floating-point result.
    12351211Floating-point exponentiation\index{exponentiation!floating point} is performed using \Index{logarithm}s\index{exponentiation!logarithm}, so the base cannot be negative.
    14461422int w, x, y, z, & ar[3] = { x, y, z }; §\C{// initialize array of references}§
    14471423&ar[1] = &w;                                            §\C{// change reference array element}§
    1448 typeof( ar[1] ) p;                                      §\C{// (gcc) is int, i.e., the type of referenced object}§
    1449 typeof( &ar[1] ) q;                                     §\C{// (gcc) is int \&, i.e., the type of reference}§
    1450 sizeof( ar[1] ) == sizeof( int );       §\C{// is true, i.e., the size of referenced object}§
    1451 sizeof( &ar[1] ) == sizeof( int *)      §\C{// is true, i.e., the size of a reference}§
     1424typeof( ar[1] ) p;                                      §\C{// (gcc) is int, \ie the type of referenced object}§
     1425typeof( &ar[1] ) q;                                     §\C{// (gcc) is int \&, \ie the type of reference}§
     1426sizeof( ar[1] ) == sizeof( int );       §\C{// is true, \ie the size of referenced object}§
     1427sizeof( &ar[1] ) == sizeof( int *)      §\C{// is true, \ie the size of a reference}§
    17891765In detail, the brackets, ©[]©, enclose the result type, where each return value is named and that name is a local variable of the particular return type.\footnote{
    1790 \Index*{Michael Tiemann}, with help from \Index*{Doug Lea}, provided named return values in g++, circa 1989.}
     1766\Index*{Michael Tiemann}\index{Tiemann, Michael}, with help from \Index*{Doug Lea}\index{Lea, Doug}, provided named return values in g++, circa 1989.}
    17911767The value of each local return variable is automatically returned at routine termination.
    17921768Declaration qualifiers can only appear at the start of a routine definition, \eg:
    22462222Currently, there are no \Index{lambda} expressions, \ie unnamed routines because routine names are very important to properly select the correct routine.
     2227In C and \CFA, lists of elements appear in several contexts, such as the parameter list of a routine call.
     2229f( ®2, x, 3 + i® );                             §\C{// element list}§
     2231A list of elements is called a \newterm{tuple}, and is different from a \Index{comma expression}.
     2234\subsection{Multiple-Return-Value Functions}
     2237In standard C, functions can return at most one value.
     2238To emulate functions with multiple return values, \emph{\Index{aggregation}} and/or \emph{\Index{aliasing}} is used.
     2239In the former situation, the function designer creates a record type that combines all of the return values into a single type.
     2240For example, consider a function returning the most frequently occurring letter in a string, and its frequency.
     2241This example is complex enough to illustrate that an array is insufficient, since arrays are homogeneous, and demonstrates a potential pitfall that exists with aliasing.
     2243struct mf_ret {
     2244        int freq;
     2245        char ch;
     2248struct mf_ret most_frequent(const char * str) {
     2249        char freqs [26] = { 0 };
     2250        struct mf_ret ret = { 0, 'a' };
     2251        for (int i = 0; str[i] != '\0'; ++i) {
     2252                if (isalpha(str[i])) {        // only count letters
     2253                        int ch = tolower(str[i]);   // convert to lower case
     2254                        int idx = ch-'a';
     2255                        if (++freqs[idx] > ret.freq) {  // update on new max
     2256                          ret.freq = freqs[idx];
     2257                 = ch;
     2258                        }
     2259                }
     2260        }
     2261        return ret;
     2264const char * str = "hello world";
     2265struct mf_ret ret = most_frequent(str);
     2266printf("%s -- %d %c\n", str, ret.freq,;
     2268Of note, the designer must come up with a name for the return type and for each of its fields.
     2269Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model.
     2270That 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.
     2271As 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.
     2273In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters.
     2274The pointer parameters are assigned inside of the routine body to emulate a return.
     2275Using the same example,
     2277int most_frequent(const char * str, char * ret_ch) {
     2278        char freqs [26] = { 0 };
     2279        int ret_freq = 0;
     2280        for (int i = 0; str[i] != '\0'; ++i) {
     2281                if (isalpha(str[i])) {        // only count letters
     2282                        int ch = tolower(str[i]);   // convert to lower case
     2283                        int idx = ch-'a';
     2284                        if (++freqs[idx] > ret_freq) {  // update on new max
     2285                          ret_freq = freqs[idx];
     2286                          *ret_ch = ch;   // assign to out parameter
     2287                        }
     2288                }
     2289        }
     2290        return ret_freq;  // only one value returned directly
     2293const char * str = "hello world";
     2294char ch;                            // pre-allocate return value
     2295int freq = most_frequent(str, &ch); // pass return value as out parameter
     2296printf("%s -- %d %c\n", str, freq, ch);
     2298Notably, 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.
     2299Also, 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.
     2300Furthermore, 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.
     2301On 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.
     2302Interestingly, there 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.
     2303In this particular case, it turns out that the frequency return value also doubles as an error code, where a frequency of 0 means the character return value should be ignored.
     2304Still, not every routine with multiple return values should be required to return an error code, and error codes are easily ignored, so this is not a satisfying solution.
     2305As with the previous approach, this technique can simulate multiple return values, but in practice it is verbose and error prone.
     2307In \CFA, functions can be declared to return multiple values with an extension to the function declaration syntax.
     2308Multiple 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.
     2309The ability to return multiple values from a function requires a new syntax for the return statement.
     2310For consistency, the return statement in \CFA accepts a comma-separated list of expressions in square brackets.
     2311The 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.
     2312A multiple-returning function with return type ©T© can return any expression that is implicitly convertible to ©T©.
     2313Using the running example, the ©most_frequent© function can be written using multiple return values as such,
     2315[int, char] most_frequent(const char * str) {
     2316        char freqs [26] = { 0 };
     2317        int ret_freq = 0;
     2318        char ret_ch = 'a';  // arbitrary default value for consistent results
     2319        for (int i = 0; str[i] != '\0'; ++i) {
     2320                if (isalpha(str[i])) {        // only count letters
     2321                        int ch = tolower(str[i]);   // convert to lower case
     2322                        int idx = ch-'a';
     2323                        if (++freqs[idx] > ret_freq) {  // update on new max
     2324                          ret_freq = freqs[idx];
     2325                          ret_ch = ch;
     2326                        }
     2327                }
     2328        }
     2329        return [ret_freq, ret_ch];
     2332This 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.
     2334The addition of multiple-return-value functions necessitates a syntax for accepting multiple values at the call-site.
     2335The simplest mechanism for retaining a return value in C is variable assignment.
     2336By assigning the return value into a variable, its value can be retrieved later at any point in the program.
     2337As such, \CFA allows assigning multiple values from a function into multiple variables, using a square-bracketed list of lvalue expressions on the left side.
     2339const char * str = "hello world";
     2340int freq;
     2341char ch;
     2342[freq, ch] = most_frequent(str);  // assign into multiple variables
     2343printf("%s -- %d %c\n", str, freq, ch);
     2345It is also common to use a function's output as the input to another function.
     2346\CFA also allows this case, without any new syntax.
     2347When 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}.
     2348For example,
     2350void process(int);       // (1)
     2351void process(char);      // (2)
     2352void process(int, char); // (3)
     2353void process(char, int); // (4)
     2355process(most_frequent("hello world"));  // selects (3)
     2357In this case, there is only one option for a function named ©most_frequent© that takes a string as input.
     2358This function returns two values, one ©int© and one ©char©.
     2359There 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.
     2360This 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.
     2362\section{Tuple Expressions}
     2363Multiple-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.
     2364These notions can be generalized to provide \CFA with \emph{tuple expressions} and \emph{tuple types}.
     2365A tuple expression is an expression producing a fixed-size, ordered list of values of heterogeneous types.
     2366The type of a tuple expression is the tuple of the subexpression types, or a \emph{tuple type}.
     2367In \CFA, a tuple expression is denoted by a comma-separated list of expressions enclosed in square brackets.
     2368For example, the expression ©[5, 'x', 10.5]© has type ©[int, char, double]©.
     2369The previous expression has 3 \emph{components}.
     2370Each component in a tuple expression can be any \CFA expression, including another tuple expression.
     2371The order of evaluation of the components in a tuple expression is unspecified, to allow a compiler the greatest flexibility for program optimization.
     2372It is, however, guaranteed that each component of a tuple expression is evaluated for side-effects, even if the result is not used.
     2373Multiple-return-value functions can equivalently be called \emph{tuple-returning functions}.
     2375\subsection{Tuple Variables}
     2376The 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.
     2377In \CFA, it is possible to overcome this restriction by declaring a \emph{tuple variable}.
     2378\begin{cfa}[emph=ret, emphstyle=\color{red}]
     2379const char * str = "hello world";
     2380[int, char] ret = most_frequent(str);  // initialize tuple variable
     2381printf("%s -- %d %c\n", str, ret);
     2383It 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.
     2384These variables can be used in any of the contexts where a tuple expression is allowed, such as in the ©printf© function call.
     2385As in the ©process© example, the components of the tuple value are passed as separate parameters to ©printf©, allowing very simple printing of tuple expressions.
     2386One way to access the individual components is with a simple assignment, as in previous examples.
     2388int freq;
     2389char ch;
     2390[freq, ch] = ret;
     2394In addition to variables of tuple type, it is also possible to have pointers to tuples, and arrays of tuples.
     2395Tuple types can be composed of any types, except for array types, since array assignment is disallowed, which makes tuple assignment difficult when a tuple contains an array.
     2397[double, int] di;
     2398[double, int] * pdi
     2399[double, int] adi[10];
     2401This examples declares a variable of type ©[double, int]©, a variable of type pointer to ©[double, int]©, and an array of ten ©[double, int]©.
     2404\subsection{Tuple Indexing}
     2406At times, it is desirable to access a single component of a tuple-valued expression without creating unnecessary temporary variables to assign to.
     2407Given 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©.
     2408For example,
     2410[int, double] x;
     2411[char *, int] f();
     2412void g(double, int);
     2413[int, double] * p;
     2415int y = x.0;                                                    §\C{// access int component of x}§
     2416y = f().1;                                                              §\C{// access int component of f}§
     2417p->0 = 5;                                                               §\C{// access int component of tuple pointed-to by p}§
     2418g( x.1, x.0 );                                                  §\C{// rearrange x to pass to g}§
     2419double z = [x, f()].0.1;                                §\C{// access second component of first component of tuple expression}§
     2421As 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.
     2422This feature was proposed for \KWC but never implemented \cite[p.~45]{Till89}.
     2424\subsection{Flattening and Structuring}
     2425As evident in previous examples, tuples in \CFA do not have a rigid structure.
     2426In function call contexts, tuples support implicit flattening and restructuring conversions.
     2427Tuple flattening recursively expands a tuple into the list of its basic components.
     2428Tuple structuring packages a list of expressions into a value of tuple type.
     2430int f(int, int);
     2431int g([int, int]);
     2432int h(int, [int, int]);
     2433[int, int] x;
     2434int y;
     2436f(x);      // flatten
     2437g(y, 10);  // structure
     2438h(x, y);   // flatten & structure
     2440In \CFA, each of these calls is valid.
     2441In the call to ©f©, ©x© is implicitly flattened so that the components of ©x© are passed as the two arguments to ©f©.
     2442For 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©.
     2443Finally, in the call to ©h©, ©x© 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]©.
     2444The 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.
     2446In \KWC \cite{Buhr94a,Till89}, there were 4 tuple coercions: opening, closing, flattening, and structuring.
     2447Opening coerces a tuple value into a tuple of values, while closing converts a tuple of values into a single tuple value.
     2448Flattening coerces a nested tuple into a flat tuple, \ie it takes a tuple with tuple components and expands it into a tuple with only non-tuple components.
     2449Structuring moves in the opposite direction, \ie it takes a flat tuple value and provides structure by introducing nested tuple components.
     2451In \CFA, the design has been simplified to require only the two conversions previously described, which trigger only in function call and return situations.
     2452This simplification is a primary contribution of this thesis to the design of tuples in \CFA.
     2453Specifically, the expression resolution algorithm examines all of the possible alternatives for an expression to determine the best match.
     2454In resolving a function call expression, each combination of function value and list of argument alternatives is examined.
     2455Given a particular argument list and function value, the list of argument alternatives is flattened to produce a list of non-tuple valued expressions.
     2456Then the flattened list of expressions is compared with each value in the function's parameter list.
     2457If 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.
     2458If 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.
     2459Assuming 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.
     2460For example, in
     2462int f(int, [double, int]);
     2463f([5, 10.2], 4);
     2465There is only a single definition of ©f©, and 3 arguments with only single interpretations.
     2466First, the argument alternative list ©[5, 10.2], 4© is flattened to produce the argument list ©5, 10.2, 4©.
     2467Next, the parameter matching algorithm begins, with $P = $©int© and $A = $©int©, which unifies exactly.
     2468Moving to the next parameter and argument, $P = $©[double, int]© and $A = $©double©.
     2469This time, the parameter is a tuple type, so the algorithm applies recursively with $P' = $©double© and $A = $©double©, which unifies exactly.
     2470Then $P' = $©int© and $A = $©double©, which again unifies exactly.
     2471At this point, the end of $P'$ has been reached, so the arguments ©10.2, 4© are structured into the tuple expression ©[10.2, 4]©.
     2472Finally, the end of the parameter list $P$ has also been reached, so the final expression is ©f(5, [10.2, 4])©.
     2474\section{Tuple Assignment}
     2476An assignment where the left side of the assignment operator has a tuple type is called tuple assignment.
     2477There 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.
     2479int x;
     2480double y;
     2481[int, double] z;
     2482[y, x] = 3.14;  // mass assignment
     2483[x, y] = z;     // multiple assignment
     2484z = 10;         // mass assignment
     2485z = [x, y];     // multiple assignment
     2487Let $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.
     2489For a multiple assignment to be valid, both tuples must have the same number of elements when flattened.
     2490For example, the following is invalid because the number of components on the left does not match the number of components on the right.
     2492[int, int] x, y, z;
     2493[x, y] = z;   // multiple assignment, invalid 4 != 2
     2495Multiple assignment assigns $R_i$ to $L_i$ for each $i$.
     2496That is, ©?=?(&$L_i$, $R_i$)© must be a well-typed expression.
     2497In 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.
     2499A mass assignment assigns the value $R$ to each $L_i$.
     2500For a mass assignment to be valid, ©?=?(&$L_i$, $R$)© must be a well-typed expression.
     2501These semantics differ from C cascading assignment (\eg ©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.
     2502For 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©.
     2503On 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.
     2505Both 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.
     2506As a result, it is possible to swap the values in two variables without explicitly creating any temporary variables or calling a function.
     2508int x = 10, y = 20;
     2509[x, y] = [y, x];
     2511After executing this code, ©x© has the value ©20© and ©y© has the value ©10©.
     2513In \CFA, tuple assignment is an expression where the result type is the type of the left side of the assignment, as in normal assignment.
     2514That is, a tuple assignment produces the value of the left-hand side after assignment.
     2515These semantics allow cascading tuple assignment to work out naturally in any context where a tuple is permitted.
     2516These 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.
     2517Restricting tuple assignment to statements was an attempt to to fix what was seen as a problem with side-effects, wherein assignment can be used in many different locations, such as in function-call argument position.
     2518While 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.
     2519Furthermore, 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.
     2520In 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.
     2521In addition, \KWC permits the compiler to optimize tuple assignment as a block copy, since it does not support user-defined assignment operators.
     2522This optimization could be implemented in \CFA, but it requires the compiler to verify that the selected assignment operator is trivial.
     2524The following example shows multiple, mass, and cascading assignment used in one expression
     2526        int a, b;
     2527        double c, d;
     2528        [void] f([int, int]);
     2529        f([c, a] = [b, d] = 1.5);  // assignments in parameter list
     2531The 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.
     2532That tuple is used as the right side of the multiple assignment (\ie, ©[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]©.
     2533Finally, the tuple ©[1, 1]© is used as an expression in the call to ©f©.
     2535\subsection{Tuple Construction}
     2536Tuple 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.
     2537As constructors and destructors did not exist in previous versions of \CFA or in \KWC, this is a primary contribution of this thesis to the design of tuples.
     2539struct S;
     2540void ?{}(S *);         // (1)
     2541void ?{}(S *, int);    // (2)
     2542void ?{}(S * double);  // (3)
     2543void ?{}(S *, S);      // (4)
     2545[S, S] x = [3, 6.28];  // uses (2), (3), specialized constructors
     2546[S, S] y;              // uses (1), (1), default constructor
     2547[S, S] z = x.0;        // uses (4), (4), copy constructor
     2549In this example, ©x© is initialized by the multiple constructor calls ©?{}(&x.0, 3)© and ©?{}(&x.1, 6.28)©, while ©y© is initialized by two default constructor calls ©?{}(&y.0)© and ©?{}(&y.1)©.
     2550©z© is initialized by mass copy constructor calls ©?{}(&z.0, x.0)© and ©?{}(&z.1, x.0)©.
     2551Finally, ©x©, ©y©, and ©z© are destructed, \ie the calls ©^?{}(&x.0)©, ©^?{}(&x.1)©, ©^?{}(&y.0)©, ©^?{}(&y.1)©, ©^?{}(&z.0)©, and ©^?{}(&z.1)©.
     2553It 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.
     2554For example, the function ©void ?{}([T, U] *, S);© can be defined to allow a tuple variable to be constructed from a value of type ©S©.
     2556struct S { int x; double y; };
     2557void ?{}([int, double] * this, S s) {
     2558        this->0 = s.x;
     2559        this->1 = s.y;
     2562Due 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.
     2563For example,
     2565struct S { int x; double y; int z };
     2566[int, double] t;
     2567S s = t;
     2569The 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.
     2571\section{Member-Access Tuple Expression}
     2573It is possible to access multiple fields from a single expression using a \emph{Member-Access Tuple Expression}.
     2574The result is a single tuple-valued expression whose type is the tuple of the types of the members.
     2575For example,
     2577struct S { int x; double y; char * z; } s;
     2578s.[x, y, z];
     2580Here, the type of ©s.[x, y, z]© is ©[int, double, char *]©.
     2581A 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.
     2582Then the type of ©a.[x, y, z]© is ©[T_x, T_y, T_z]©.
     2584Since 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 (\eg, rearrange components, drop components, duplicate components, etc.).
     2586[int, int, long, double] x;
     2587void f(double, long);
     2589f(x.[0, 3]);          // f(x.0, x.3)
     2590x.[0, 1] = x.[1, 0];  // [x.0, x.1] = [x.1, x.0]
     2591[long, int, long] y = x.[2, 0, 2];
     2594It is possible for a member tuple expression to contain other member access expressions.
     2595For example,
     2597struct A { double i; int j; };
     2598struct B { int * k; short l; };
     2599struct C { int x; A y; B z; } v;
     2600v.[x, y.[i, j], z.k];
     2602This expression is equivalent to ©[v.x, [v.y.i, v.y.j], v.z.k]©.
     2603That is, the aggregate expression is effectively distributed across the tuple, which allows simple and easy access to multiple components in an aggregate, without repetition.
     2604It is guaranteed that the aggregate expression to the left of the ©.© in a member tuple expression is evaluated exactly once.
     2605As such, it is safe to use member tuple expressions on the result of a side-effecting function.
     2607[int, float, double] f();
     2608[double, float] x = f().[2, 1];
     2611In \KWC, member tuple expressions are known as \emph{record field tuples} \cite{Till89}.
     2612Since \CFA permits these tuple-access expressions using structures, unions, and tuples, \emph{member tuple expression} or \emph{field tuple expression} is more appropriate.
     2614It is possible to extend member-access expressions further.
     2615Currently, 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.
     2616In the interest of orthogonal design, \CFA could apply some meaning to the remaining combinations as well.
     2617For example,
     2619struct S { int x, y; } s;
     2620[S, S] z;
     2622s.x;  // access member
     2623z.0;  // access component
     2625s.1;  // ???
     2626z.y;  // ???
     2628One possibility is for ©s.1© to select the second member of ©s©.
     2629Under this interpretation, it becomes possible to not only access members of a struct by name, but also by position.
     2630Likewise, it seems natural to open this mechanism to enumerations as well, wherein the left side would be a type, rather than an expression.
     2631One benefit of this interpretation is familiarity, since it is extremely reminiscent of tuple-index expressions.
     2632On 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.
     2633This 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.
     2635As for ©z.y©, one interpretation is to extend the meaning of member tuple expressions.
     2636That is, currently the tuple must occur as the member, \ie to the right of the dot.
     2637Allowing 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.
     2638In 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©.
     2639It 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.
     2640Perhaps 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.
     2641The 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.
     2643Supposing this feature works as described, it would be necessary to specify an ordering for the expansion of member-access expressions versus member-tuple expressions.
     2645struct { int x, y; };
     2646[S, S] z;
     2647z.[x, y];  // ???
     2648// => [z.0, z.1].[x, y]
     2649// => [z.0.x, z.0.y, z.1.x, z.1.y]
     2650// or
     2651// => [z.x, z.y]
     2652// => [[z.0, z.1].x, [z.0, z.1].y]
     2653// => [z.0.x, z.1.x, z.0.y, z.1.y]
     2655Depending on exactly how the two tuples are combined, different results can be achieved.
     2656As such, a specific ordering would need to be imposed to make this feature useful.
     2657Furthermore, 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.
     2659A second possibility is for \CFA to have named tuples, as they exist in Swift and D.
     2661typedef [int x, int y] Point2D;
     2662Point2D p1, p2;
     2663p1.x + p1.y + p2.x + p2.y;
     2664p1.0 + p1.1 + p2.0 + p2.1;  // equivalent
     2666In this simpler interpretation, a tuple type carries with it a list of possibly empty identifiers.
     2667This approach fits naturally with the named return-value feature, and would likely go a long way towards implementing it.
     2669Ultimately, the first two extensions introduce complexity into the model, with relatively little perceived benefit, and so were dropped from consideration.
     2670Named tuples are a potentially useful addition to the language, provided they can be parsed with a reasonable syntax.
     2674In C, the cast operator is used to explicitly convert between types.
     2675In \CFA, the cast operator has a secondary use, which is type ascription, since it forces the expression resolution algorithm to choose the lowest cost conversion to the target type.
     2676That 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.
     2678int f();     // (1)
     2679double f();  // (2)
     2681f();       // ambiguous - (1),(2) both equally viable
     2682(int)f();  // choose (2)
     2684Since casting is a fundamental operation in \CFA, casts need to be given a meaningful interpretation in the context of tuples.
     2685Taking a look at standard C provides some guidance with respect to the way casts should work with tuples.
     2687int f();
     2688void g();
     2690(void)f();  // valid, ignore results
     2691(int)g();   // invalid, void cannot be converted to int
     2693struct A { int x; };
     2694(struct A)f();  // invalid, int cannot be converted to A
     2696In C, line 4 is a valid cast, which calls ©f© and discards its result.
     2697On the other hand, line 5 is invalid, because ©g© does not produce a result, so requesting an ©int© to materialize from nothing is nonsensical.
     2698Finally, line 8 is also invalid, because in C casts only provide conversion between scalar types \cite[p.~91]{C11}.
     2699For 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.
     2701Formally, 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$.
     2702Excess 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.
     2703This discarding naturally follows the way that a cast to void works in C.
     2705For example,
     2707        [int, int, int] f();
     2708        [int, [int, int], int] g();
     2710        ([int, double])f();           // (1) valid
     2711        ([int, int, int])g();         // (2) valid
     2712        ([void, [int, int]])g();      // (3) valid
     2713        ([int, int, int, int])g();    // (4) invalid
     2714        ([int, [int, int, int]])g();  // (5) invalid
     2717(1) discards the last element of the return value and converts the second element to type double.
     2718Since ©int© is effectively a 1-element tuple, (2) discards the second component of the second element of the return value of ©g©.
     2719If ©g© is free of side effects, this is equivalent to ©[(int)(g().0), (int)(g().1.0), (int)(g().2)]©.
     2720Since ©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)]©).
     2721% 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).
     2722Note that a cast is not a function call in \CFA, so flattening and structuring conversions do not occur for cast expressions.
     2723As such, (4) is invalid because the cast target type contains 4 components, while the source type contains only 3.
     2724Similarly, (5) is invalid because the cast ©([int, int, int])(g().1)© is invalid.
     2725That is, it is invalid to cast ©[int, int]© to ©[int, int, int]©.
     2728Due to the implicit flattening and structuring conversions involved in argument passing, ©otype© and ©dtype© parameters are restricted to matching only with non-tuple types.
     2729The integration of polymorphism, type assertions, and monomorphic specialization of tuple-assertions are a primary contribution of this thesis to the design of tuples.
     2731forall(otype T, dtype U)
     2732void f(T x, U * y);
     2734f([5, "hello"]);
     2736In this example, ©[5, "hello"]© is flattened, so that the argument list appears as ©5, "hello"©.
     2737The argument matching algorithm binds ©T© to ©int© and ©U© to ©const char©, and calls the function as normal.
     2739Tuples can contain otype and dtype components.
     2740For example, a plus operator can be written to add two triples of a type together.
     2742forall(otype T | { T ?+?(T, T); })
     2743[T, T, T] ?+?([T, T, T] x, [T, T, T] y) {
     2744        return [x.0+y.0, x.1+y.1, x.2+y.2];
     2746[int, int, int] x;
     2747int i1, i2, i3;
     2748[i1, i2, i3] = x + ([10, 20, 30]);
     2750Note that due to the implicit tuple conversions, this function is not restricted to the addition of two triples.
     2751A 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©.
     2752For example, these expressions also succeed and produce the same value.
     2754([x.0, x.1]) + ([x.2, 10, 20, 30]);  // x + ([10, 20, 30])
     2755x.0 + ([x.1, x.2, 10, 20, 30]);      // x + ([10, 20, 30])
     2757This presents a potential problem if structure is important, as these three expressions look like they should have different meanings.
     2758Furthermore, these calls can be made ambiguous by introducing seemingly different functions.
     2760forall(otype T | { T ?+?(T, T); })
     2761[T, T, T] ?+?([T, T] x, [T, T, T, T]);
     2762forall(otype T | { T ?+?(T, T); })
     2763[T, T, T] ?+?(T x, [T, T, T, T, T]);
     2765It 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.
     2766Still, these semantics are a deficiency of the current argument matching algorithm, and depending on the function, differing return values may not always be appropriate.
     2767These issues could be rectified by applying an appropriate conversion cost to the structuring and flattening conversions, which are currently 0-cost conversions in the expression resolver.
     2768Care would be needed in this case to ensure that exact matches do not incur such a cost.
     2770void f([int, int], int, int);
     2772f([0, 0], 0, 0);    // no cost
     2773f(0, 0, 0, 0);      // cost for structuring
     2774f([0, 0,], [0, 0]); // cost for flattening
     2775f([0, 0, 0], 0);    // cost for flattening and structuring
     2778Until this point, it has been assumed that assertion arguments must match the parameter type exactly, modulo polymorphic specialization (\ie, no implicit conversions are applied to assertion arguments).
     2779This decision presents a conflict with the flexibility of tuples.
     2780\subsection{Assertion Inference}
     2782int f([int, double], double);
     2783forall(otype T, otype U | { T f(T, U, U); })
     2784void g(T, U);
     2785g(5, 10.21);
     2787If 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.
     2788Since tuples are fluid, this requirement reduces the usability of tuples in polymorphic code.
     2789To 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.
     2791This relaxation is made possible by extending the existing thunk generation scheme, as described by Bilson \cite{Bilson03}.
     2792Now, 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.
     2794int _thunk(int _p0, double _p1, double _p2) {
     2795        return f([_p0, _p1], _p2);
     2798Essentially, this provides flattening and structuring conversions to inferred functions, improving the compatibility of tuples and polymorphism.
    32313783\section{Auto Type-Inferencing}
    3233 Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type.
     3785Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization ex\-pression type.
    3262 preventing having to determine or write out long generic types,
     3814preventing having to determine or write long generic types,
    32643816ensure secondary variables, related to a primary variable, always have the same type.
    32843836There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type.
    32853837That is, when is the type of the variable more important than the type of its initialization expression.
    3286 For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors.
    3287 At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes.
     3838For example, if a change is made in an initialization expression, it can cause significant cascading type changes and/or errors.
     3839At some point, a variable type needs to remain constant and the expression to be in error when it changes.
    32893841Given ©typedef© and ©typeof© in \CFA, and the strong need to use the type of left-hand side in inferencing, auto type-inferencing is not supported at this time.
    34984050        }
    3500 \end{comment}
    3503 \subsection{Memory Management}
    3506 \subsubsection{Manual Memory Management}
    3508 Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
    3509 First, malloc breaks type safety because it returns a pointer to void.
    3510 There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
    3511 This problem is solved with a type-safe malloc.
    3512 Do.s type-safe malloc does not take any arguments for size.
    3513 Instead, it infers the type based on the return value, and then allocates space for the inferred type.
    3515 \begin{cfa}
    3516 float *f = malloc(); // allocates the size of a float
    3518 struct S {
    3519         int i, j, k;
    3520 };
    3522 struct S *s = malloc(); // allocates the size of a struct S
    3523 \end{cfa}
    3525 In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
    3526 For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
    3528 \begin{cfa}
    3529 type Complex = struct {
    3530         float real;
    3531         float imag;
    3532 };
    3534 // default constructor
    3536 void ?{}(Complex &c) {
    3537         c.real = 0.0;
    3538         c.imag = 0.0;
    3539 }
    3543 // 2 parameter constructor
    3545 void ?{}(Complex &c, float real, float imag) {
    3546         c.real = real;
    3547         c.imag = imag;
    3548 }
    3551 int main() {
    3552         Complex c1; // No constructor is called
    3553         Complex c2{}; // Default constructor called
    3554         Complex c3{1.0, -1.0}; // 2 parameter constructor is called
    3556         Complex *p1 = malloc(); // allocate
    3557         Complex *p2 = new(); // allocate + default constructor
    3558         Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
    3559 }
    3560 \end{cfa}
    3563 \subsubsection{Automatic Memory Management}
    3565 \CFA may also support automatic memory management to further improve safety.
    3566 If the compiler can insert all of the code needed to manage dynamically allocated memory (automatic reference counting), then developers can avoid problems with dangling pointers, double frees, memory leaks, etc.
    3567 This feature requires further investigation.
    3568 \CFA will not have a garbage collector, but might use some kind of region-based memory management.
    3571 \begin{comment}
    3572 \subsection{Unsafe C Constructs}
    3574 C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
    3575 Some of these practices however are often error-prone and difficult to read and maintain.
    3576 Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
    3577 If a programmer wants to use one of these unsafe C constructs, the unsafe code must be contained in a C linkage block (see Interoperability), which will be compiled like C code.
    3578 This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
    3580 The exact set of unsafe C constructs that will be disallowed in \CFA has not yet been decided, but is sure to include pointer arithmetic, pointer casting, etc.
    3581 Once the full set is decided, the rules will be listed here.
    3807 \begin{comment}
    3808 \begin{cfa}
    3809 type Adder = task {
    3810         int *row;
    3811         int size;
    3812         int &subtotal;
    3813 }
    3814 \end{cfa}
    3816 A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
    3817 A destructor may also be defined, which is called at deallocation (when a dynamic object is deleted or when a local object goes out of scope).
    3818 After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
    3819 All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
    3820 Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
    3821 (Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
    3822 \begin{cfa}
    3823 void ?{}(Adder &a, int r[], int s, int &st) { // constructor
    3824         a.row = r;
    3825         a.size = s;
    3826         a.subtotal = st;
    3827 }
    3829 // implicitly spawn thread and begin execution here
    3831 void ?()(Adder &a) {
    3832         int c;
    3833         subtotal = 0;
    3834         for (c=0; c<a.size; ++c) {
    3835         subtotal += row[c];
    3836         }
    3837 }
    3839 int main() {
    3840         const int rows = 100, cols = 1000000;
    3841         int matrix[rows][cols];
    3842         int subtotals[rows];
    3843         int total = 0;
    3844         int r;
    3846         { // create a new scope here for our adders
    3847         Adder adders[rows];
    3848         // read in the matrix
    3849         ...
    3850         for (r=0; r<rows; ++r) {
    3851         // tasks are initialized on this thread
    3852         Adders[r] = {matrix[r], cols, subtotals[r]};
    3853         Adders[r](); // spawn thread and begin execution
    3854         }
    3855         } // adders go out of scope; block here until they all finish
    3856         total += subtotals[r];
    3857         printf(.total is %d\n., total);
    3858 }
    3859 \end{cfa}
    3861 \subsection{Cooperative Scheduling}
    3863 Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
    3864 In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
    3865 Places where a task could yield include waiting for a lock (explicitly or implicitly), waiting for I/O, or waiting for a specific function (or one of a set of functions) to be called.
    3866 This last option is introduced with the yield function. yield is used to indicate that this task should yield its thread until the specified function is called.
    3867 For example, the code below defines a monitor that maintains a generic list.
    3868 When a task tries to pop from the list, but it is empty, the task should yield until another task puts something into the list, with the push function.
    3869 Similarly, when a task tries to push something onto the list, but it is full, it will yield until another task frees some space with the pop function.
    3871 \begin{cfa}
    3872 // type T is used as a generic type for all definitions inside
    3873 // the curly brackets
    3875 generic(type T) {
    3876         type Channel = monitor {
    3877         List(T) list; // list is a simple generic list type
    3878         };
    3880         T pop(mutex &Channel(T) ch) {
    3881         if (ch.list.empty()) {
    3882         // yield until push is called for this channel
    3883         yield(push);
    3884         }
    3885         return ch.list.pop();
    3886         }
    3888         void push(mutex &Channel(T)ch, T val) {
    3889         if (ch.list.full()) {
    3890         // yield until pop is called for this channel
    3891         yield(pop);
    3892         }
    3893         ch.list.push(val);
    3894         }
    3895 }
    3896 \end{cfa}
    3898 A task can also yield indefinitely by calling yield with no arguments.
    3899 This will tell the scheduler to yield this task until it is resumed by some other task.
    3900 A task can resume another task by using its functional call operator.
    3901 The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
    3903 \begin{cfa}
    3904 type Ping = task {
    3905         Pong *partner;
    3906 };
    3908 void ?{}(Ping &p, Pong *partner = 0) {
    3909         p.partner = partner;
    3910 }
    3912 void ?()(Ping &p) {
    3913         for(;;) { // loop forever
    3914         printf(.ping\n.);
    3915         partner(); // resumes the partner task
    3916         yield(); // yields this task
    3917         }
    3918 }
    3920 type Pong = task {
    3921         Ping *partner;
    3922 };
    3924 void ?{}(Pong &p, Ping *partner = 0) {
    3925         p.partner = partner;
    3926 }
    3928 void ?()(Pong &p) {
    3929         for(;;) { // loop forever
    3930         yield(); // yields this task
    3931         printf(.pong/n.);
    3932         partner(); // resumes the partner task
    3933         }
    3934 }
    3936 void main() {
    3937         Ping ping; // allocate ping
    3938         Pong pong{ping}; // allocate, initialize, and start pong
    3939         Ping{pong}; // initialize and start ping
    3940 }
    3941 \end{cfa}
    3943 The same functionality can be accomplished by providing functions to be called by the partner task.
    3944 \begin{cfa}
    3945 type Pingpong = task {
    3946         String msg;
    3947         Pingpong *partner;
    3948 };
    3950 void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
    3951         p.msg = msg;
    3952         p.partner = partner;
    3953 }
    3955 void ?()(Pingpong &p) {
    3956         for(;;) {
    3957         yield(go);
    3958         }
    3959 }
    3961 void go(Pingpong &p) {
    3962         print(.%(p.msg)\n.);
    3963         go(p.partner);
    3964 }
    3966 void main() {
    3967         Pingpong ping = {.ping.};
    3968         Pingpong pong = {.pong., ping};
    3969         ping.partner = pong;
    3970         go(ping);
    3971 }
    3972 \end{cfa}
    3973 \end{comment}
    4634 \section{Comparison with Other Languages}
     4935\section{Language Comparisons}
    46364937\CFA is one of many languages that attempts to improve upon C.
    5369 \section{\texorpdfstring{\CFA Keywords}{Cforall Keywords}}
    5370 \label{s:CFAKeywords}
    5372 \CFA introduces the following new keywords.
    5374 \begin{quote2}
    5375 \begin{tabular}{lllll}
    5376 \begin{tabular}{@{}l@{}}
    5377 ©_At©                   \\
    5378 ©catch©                 \\
    5379 ©catchResume©   \\
    5380 ©choose©                \\
    5381 ©coroutine©             \\
    5382 \end{tabular}
    5383 &
    5384 \begin{tabular}{@{}l@{}}
    5385 ©disable©               \\
    5386 ©dtype©                 \\
    5387 ©enable©                \\
    5388 ©fallthrough©   \\
    5389 ©fallthru©              \\
    5390 \end{tabular}
    5391 &
    5392 \begin{tabular}{@{}l@{}}
    5393 ©finally©               \\
    5394 ©forall©                \\
    5395 ©ftype©                 \\
    5396 ©lvalue©                \\
    5397 ©monitor©               \\
    5398 \end{tabular}
    5399 &
    5400 \begin{tabular}{@{}l@{}}
    5401 ©mutex©                 \\
    5402 ©one_t©                 \\
    5403 ©otype©                 \\
    5404 ©throw©                 \\
    5405 ©throwResume©   \\
    5406 \end{tabular}
    5407 &
    5408 \begin{tabular}{@{}l@{}}
    5409 ©trait©                 \\
    5410 ©try©                   \\
    5411 ©ttype©                 \\
    5412 ©with©                  \\
    5413 ©zero_t©                \\
    5414 \end{tabular}
    5415 \end{tabular}
    5416 \end{quote2}
    5419 \section{Incompatible}
     5670\section{C Incompatibles}
    54215672The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{C++14}.
    55185769struct X { int i; struct X *next; };
    55195770static struct X a;                              §\C{// forward definition}§
    5520 static struct X b = { 0, ®&a® };        §\C{// forward reference, valid in C, invalid in \CFA}§
     5771static struct X b = { 0, ®&a® };§\C{// forward reference, valid in C, invalid in \CFA}§
    55215772static struct X a = { 1, &b };  §\C{// definition}§
    55335784enum ®Colour® { R, G, B, Y, C, M };
    55345785struct Person {
    5535         enum ®Colour® { R, G, B };      §\C{// nested type}§
     5786        enum ®Colour® { R, G, B };      §\C[7cm]{// nested type}§
    55365787        struct Face {                           §\C{// nested type}§
    55375788                ®Colour® Eyes, Hair;    §\C{// type defined outside (1 level)}§
    55435794®Colour® c = R;                                 §\C{// type/enum defined same level}§
    5544 Person®.Colour® pc = Person®.®R;        §\C{// type/enum defined inside}§
    5545 Person®.®Face pretty;                   §\C{// type defined inside}§
     5795Person®.Colour® pc = Person®.®R;§\C{// type/enum defined inside}§
     5796Person®.®Face pretty;                   §\C{// type defined inside}\CRT§
    55475798In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing structure, \ie the nested types are hoisted to the scope of the outer-most type, which is not useful and confusing.
     5825\item[Change:] remove implicit conversion of ©void *© to or from any ©T *© pointer:
     5827void foo() {
     5828        int * b = malloc( sizeof(int) );        §\C{// implicitly convert void * to int *}§
     5829        char * c = b;                           §\C{// implicitly convert int * to void *, and then void * to char *}§
     5832\item[Rationale:] increase type safety
     5833\item[Effect on original feature:] deletion of semantically well-defined feature.
     5834\item[Difficulty of converting:] requires adding a cast (see \VRef{s:StorageManagement} for better alternatives):
     5836        int * b = (int *)malloc( sizeof(int) );
     5837        char * c = (char *)b;
     5839\item[How widely used:] Significant.
     5840Some C translators already give a warning if the cast is not used.
     5845\item[Change:] Types must be declared in declarations, not in expressions
     5846In C, a sizeof expression or cast expression may create a new type. For example,
     5848p = (void*)(struct x {int i;} *)0;
     5850declares a new type, struct x .
     5851\item[Rationale:] This prohibition helps to clarify the location of declarations in the source code.
     5852\item[Effect on original feature:] Deletion of a semantically welldefined feature.
     5853\item[Difficulty of converting:] Syntactic transformation.
     5854\item[How widely used:] Seldom.
    55745859\item[Change:] comma expression is disallowed as subscript
    55755860\item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new style arrays.
    55765861\item[Effect on original feature:] change to semantics of well-defined feature.
    55775862\item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]©
    5578 \item[How widely used:] seldom.
     5863\item[How widely used:] Seldom.
     5868\section{\texorpdfstring{\CFA Keywords}{Cforall Keywords}}
     5871\CFA introduces the following new keywords.
    55835878\section{Standard Headers}
    55865881\Celeven prescribes the following standard header-files~\cite[\S~7.1.2]{C11} and \CFA adds to this list:
    5588 \begin{tabular}{@{}lllll|l@{}}
    5589 \multicolumn{5}{c|}{C11} & \multicolumn{1}{c}{\CFA}             \\
     5884\multicolumn{6}{c|}{C11} & \multicolumn{1}{c}{\CFA}             \\
    55955890\Indexc{errno.h}                \\
    55965891\Indexc{fenv.h}                 \\
    5597 \Indexc[deletekeywords=float]{float.h} \\
     5895\Indexc[deletekeywords=float]{float.h} \\
    56015896\Indexc{inttypes.h}             \\
    56025897\Indexc{iso646.h}               \\
    56035898\Indexc{limits.h}               \\
    56045899\Indexc{locale.h}               \\
    5605 \Indexc{math.h}                 \\
    5606 \Indexc{setjmp.h}               \\
     5903\Indexc{math.h}                 \\
     5904\Indexc{setjmp.h}               \\
    56105905\Indexc{signal.h}               \\
    56115906\Indexc{stdalign.h}             \\
    56125907\Indexc{stdarg.h}               \\
    56135911\Indexc{stdatomic.h}    \\
    56145912\Indexc{stdbool.h}              \\
    56155913\Indexc{stddef.h}               \\
     5914\Indexc{stdint.h}               \\
     5915\Indexc{stdio.h}                \\
    5619 \Indexc{stdint.h}               \\
    5620 \Indexc{stdio.h}                \\
    56215919\Indexc{stdlib.h}               \\
    56225920\Indexc{stdnoreturn.h}  \\
    56235921\Indexc{string.h}               \\
    56245922\Indexc{tgmath.h}               \\
     5923\Indexc{threads.h}              \\
    5628 \Indexc{threads.h}              \\
    56295927\Indexc{time.h}                 \\
    56305928\Indexc{uchar.h}                \\
     5935\Indexc{gmp.h}                  \\
     5936\Indexc{malloc.h}               \\
    56375937\Indexc{unistd.h}               \\
    5638 \Indexc{gmp.h}                  \\
    5639                                                 \\
    5640                                                 \\
    56415938                                                \\
    56425939                                                \\
    56475944hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}).
    56485945All other C header files must be explicitly wrapped in ©extern "C"© to prevent name mangling.
    5649 For \Index*[C++]{\CC{}}, the name-mangling issue is handled implicitly because most C header-files are augmented with checks for preprocessor variable ©__cplusplus©, which adds appropriate ©extern "C"© qualifiers.
     5946For \Index*[C++]{\CC{}}, the name-mangling issue is often handled internally in many C header-files through checks for preprocessor variable ©__cplusplus©, which adds appropriate ©extern "C"© qualifiers.
    56585955\subsection{Storage Management}
    56605958The storage-management routines extend their C equivalents by overloading, alternate names, providing shallow type-safety, and removing the need to specify the allocation size for non-array types.
    58706168long double remainder( long double, long double );
    5872 [ int, float ] remquo( float, float );§\indexc{remquo}§
    5873 float remquo( float, float, int * );
     6170float remquo( float, float, int * );§\indexc{remquo}§
     6171double remquo( double, double, int * );
     6172long double remquo( long double, long double, int * );
     6173[ int, float ] remquo( float, float );
    58746174[ int, double ] remquo( double, double );
    5875 double remquo( double, double, int * );
    58766175[ int, long double ] remquo( long double, long double );
    5877 long double remquo( long double, long double, int * );
    5879 [ int, float ] div( float, float );                                             // alternative name for remquo
    5880 float div( float, float, int * );§\indexc{div}§
     6177float div( float, float, int * );§\indexc{div}§ §\C{// alternative name for remquo}§
     6178double div( double, double, int * );
     6179long double div( long double, long double, int * );
     6180[ int, float ] div( float, float );
    58816181[ int, double ] div( double, double );
    5882 double div( double, double, int * );
    58836182[ int, long double ] div( long double, long double );
    5884 long double div( long double, long double, int * );
    58866184float fma( float, float, float );§\indexc{fma}§
    59126210double exp2( double );
    59136211long double exp2( long double );
    5914 float _Complex exp2( float _Complex );
    5915 double _Complex exp2( double _Complex );
    5916 long double _Complex exp2( long double _Complex );
     6212// float _Complex exp2( float _Complex );
     6213// double _Complex exp2( double _Complex );
     6214// long double _Complex exp2( long double _Complex );
    59186216float expm1( float );§\indexc{expm1}§
    59206218long double expm1( long double );
     6220float pow( float, float );§\indexc{pow}§
     6221double pow( double, double );
     6222long double pow( long double, long double );
     6223float _Complex pow( float _Complex, float _Complex );
     6224double _Complex pow( double _Complex, double _Complex );
     6225long double _Complex pow( long double _Complex, long double _Complex );
    59226233float log( float );§\indexc{log}§
    59236234double log( double );
    59306241double log2( double );
    59316242long double log2( long double );
    5932 float _Complex log2( float _Complex );
    5933 double _Complex log2( double _Complex );
    5934 long double _Complex log2( long double _Complex );
     6243// float _Complex log2( float _Complex );
     6244// double _Complex log2( double _Complex );
     6245// long double _Complex log2( long double _Complex );
    59366247float log10( float );§\indexc{log10}§
    59376248double log10( double );
    59386249long double log10( long double );
    5939 float _Complex log10( float _Complex );
    5940 double _Complex log10( double _Complex );
    5941 long double _Complex log10( long double _Complex );
     6250// float _Complex log10( float _Complex );
     6251// double _Complex log10( double _Complex );
     6252// long double _Complex log10( long double _Complex );
    59436254float log1p( float );§\indexc{log1p}§
    59526263double logb( double );
    59536264long double logb( long double );
    5954 \end{cfa}
    5957 \subsection{Power}
    5959 \leavevmode
    5960 \begin{cfa}[aboveskip=0pt,belowskip=0pt]
    59616266float sqrt( float );§\indexc{sqrt}§
    59626267double sqrt( double );
    59736278double hypot( double, double );
    59746279long double hypot( long double, long double );
    5976 float pow( float, float );§\indexc{pow}§
    5977 double pow( double, double );
    5978 long double pow( long double, long double );
    5979 float _Complex pow( float _Complex, float _Complex );
    5980 double _Complex pow( double _Complex, double _Complex );
    5981 long double _Complex pow( long double _Complex, long double _Complex );
    60336331long double atan2( long double, long double );
    6035 float atan( float, float );                                                             // alternative name for atan2
     6333float atan( float, float );                                     §\C{// alternative name for atan2}§
    60366334double atan( double, double );§\indexc{atan}§
    60376335long double atan( long double, long double );
    6223 void ?{}( Int * this );                                 §\C{// constructor
     6521void ?{}( Int * this );                                 §\C{// constructor/destructor
    62246522void ?{}( Int * this, Int init );
    62256523void ?{}( Int * this, zero_t );
    64766774// implementation
    64776775struct Rational {§\indexc{Rational}§
    6478         long int numerator, denominator;                                        // invariant: denominator > 0
     6776        long int numerator, denominator;        §\C{// invariant: denominator > 0}§
    64796777}; // Rational
Note: See TracChangeset for help on using the changeset viewer.