source: doc/user/user.tex @ b52d900

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglergc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newstringwith_gc
Last change on this file since b52d900 was b52d900, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

extend user manual, update latex macros, and update reference manual

  • Property mode set to 100644
File size: 170.0 KB
Line 
1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%%
2%%
3%% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
4%%
5%% The contents of this file are covered under the licence agreement in the
6%% file "LICENCE" distributed with Cforall.
7%%
8%% user.tex --
9%%
10%% Author           : Peter A. Buhr
11%% Created On       : Wed Apr  6 14:53:29 2016
12%% Last Modified By : Peter A. Buhr
13%% Last Modified On : Sun Apr 10 22:50:15 2016
14%% Update Count     : 72
15%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
16
17% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
18
19\documentclass[openright,twoside]{article}
20%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
21
22% Latex packages used in the document.
23\usepackage[T1]{fontenc}                                % allow Latin1 (extended ASCII) characters
24\usepackage{textcomp}
25\usepackage[latin1]{inputenc}
26\usepackage{upquote}
27\usepackage{fullpage,times}
28\usepackage{xspace}
29\usepackage{varioref}
30\usepackage{listings}
31\usepackage{footmisc}
32\usepackage{comment}
33\usepackage{latexsym}                                   % \Box
34\usepackage{mathptmx}                                   % better math font with "times"
35\usepackage[pagewise]{lineno}
36\renewcommand{\linenumberfont}{\scriptsize\sffamily}
37\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
38\usepackage{breakurl}
39\renewcommand{\UrlFont}{\small\sf}
40
41%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42
43% Bespoke macros used in the document.
44\input{common}
45
46%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
47
48% Names used in the document.
49
50\newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace}
51
52%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
53
54\setcounter{secnumdepth}{3}                             % number subsubsections
55\setcounter{tocdepth}{3}                                % subsubsections in table of contents
56\makeindex
57
58%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
59
60\begin{document}
61\pagestyle{headings}
62\linenumbers                                            % comment out to turn off line numbering
63
64\title{\Huge
65\vspace*{1in}
66\CFA (\CFL) User Manual                         \\
67Version 1.0                                                     \\
68\vspace*{0.25in}
69\huge``describe not prescribe''         \\
70\vspace*{1in}
71}% title
72\author{\huge
73Peter A. Buhr and ...                           \\
74}% author
75\date{
76DRAFT \\
77\today
78}% date
79
80\pagenumbering{roman}
81\pagestyle{plain}
82
83\maketitle
84
85\vspace*{\fill}
86\thispagestyle{empty}
87\noindent
88\copyright\,2016 \CFA Project \\ \\
89\noindent
90This work is licensed under the Creative Commons Attribution 4.0 International License.
91To view a copy of this license, visit {\small\url{http://creativecommons.org/licenses/by/4.0}}.
92\vspace*{1in}
93
94\clearpage
95\pdfbookmark[1]{Contents}{section}
96\tableofcontents
97
98\clearpage
99\pagenumbering{arabic}
100
101
102\section{Introduction}
103
104\CFA\footnote{Pronounced ``C-for-all'', and written \CFA, CFA, or \CFL.} is a modern general-purpose programming-language, designed an as evolutionary step forward from the C programming language.
105The syntax of the \CFA language builds from C, and should look immediately familiar to C programmers.
106% Any language feature that is not described here can be assumed to be using the standard C11 syntax.
107\CFA adds many modern programming-language features, which directly leads to increased safety and productivity, while maintaining interoperability with existing C programs and maintaining C-like performance.
108Like C, \CFA is a statically typed, procedural language with a low-overhead runtime, meaning there is no global garbage-collection.
109The primary new features include parametric-polymorphism routines and types, exceptions, concurrency, and modules.
110
111One of the main design philosophies of \CFA is to ``describe not prescribe'', which means \CFA tries to provide a pathway from low-level C programming to high-level \CFA programming, but it does not force programmers to ``do the right thing''.
112Programmers can cautiously add \CFA extensions to their C programs in any order and at any time to incrementally move towards safer, higher-level programming features.
113A programmer is always free to reach back to C from \CFA for any reason, and in many cases, new \CFA features have a fallback to a C mechanism.
114There is no notion or requirement for rewriting a legacy C program in \CFA;
115instead, a programmer evolves an existing C program into \CFA by incrementally incorporating \CFA features.
116New programs can be written in \CFA using a combination of C and \CFA features.
117\CC had a similar goal 30 years ago, but has struggled over the intervening time to incorporate modern programming-language features because of early design choices.
118\CFA has 30 years of hindsight and clean starting point.
119
120Like \CC, there may be both an old and new ways to achieve the same effect.
121For example, the following programs compare the \CFA and C I/O mechanisms.
122\begin{quote2}
123\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
124\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
125\begin{lstlisting}
126#include <fstream>
127int main( void ) {
128        int x = 0, y = 1, z = 2;
129        sout | x | y | z | endl;
130}
131\end{lstlisting}
132&
133\begin{lstlisting}
134#include <stdio.h>
135int main( void ) {
136        int x = 0, y = 1, z = 2;
137        printf( "%d %d %d\n", x, y, z );
138}
139\end{lstlisting}
140\end{tabular}
141\end{quote2}
142Both programs output the same result.
143While the \CFA I/O looks similar to the \CC output style, there are several important differences, such as automatic spacing between variables as in Python (see also~\VRef{s:IOLibrary}).
144
145This document is a reference manual for the \CFA programming language, targeted at \CFA programmers.
146Implementers may refer to the \CFA Programming Language Specification for details about the language syntax and semantics.
147In its current state, this document covers the intended core features of the language.
148Changes to the syntax and additional features are expected to be included in later revisions.
149% For additional information, see \url{http://wiki.do-lang.org}.
150
151
152\section{History}
153
154The \CFA project started with K-W C~\cite{Till89,Buhr94a}, which extended C with new declaration syntax, multiple return values from routines, and extended assignment capabilities using the notion of tuples.
155(See~\cite{Werther96} for some similar work, but for \CC.)
156The original \CFA project~\cite{Ditchfield92} extended the C type system with parametric polymorphism and overloading, as opposed to the \CC approach of object-oriented extensions to the C type-system.
157A first implementation of the core Cforall language was created~\cite{Bilson03,Esteves04}, but at the time there was little interesting in extending C, so work did not continue.
158As the saying goes, ``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.
159
160
161\section{Why fix C?}
162
163Even with all its problems, C is a very popular programming language because it allows writing software at virtually any level in a computer system without restriction.
164For systems programming, where direct access to hardware and dealing with real-time issues is a requirement, C is usually the language of choice.
165As well, there are millions of lines of C legacy code, forming the base for many software development projects (especially on UNIX systems).
166The TIOBE index (\url{http://www.tiobe.com/tiobe_index}) for March 2016 shows programming-language popularity, with Java 20.5\%, C 14.5\%, \CC 6.7\%, \CS 4.3\%, Python 4.3\%, and all other programming languages below 3\%.
167Hence, C is still an extremely important programming language, with double the usage of \CC, where \CC itself is largely C code.
168Finally, love it or hate it, C has been an important and influential part of computer science for 40 years and it appears it will continue to be for many more years.
169Unfortunately, C has too many problems and omissions to make it an acceptable programming language for modern needs.
170
171The goal of this project is to engineer modern language features into C in an evolutionary rather than revolutionary way.
172\CC~\cite{c++,ANSI14:C++} is an example of a similar project;
173however, it largely extended the language, and did not address existing problems.\footnote{%
174Two important existing problems addressed were changing the type of character literals from \lstinline@int@ to \lstinline@char@ and enumerator from \lstinline@int@ to the type of its enumerators.}
175Fortran~\cite{Fortran08}, Ada~\cite{Ada12}, and Cobol~\cite{Cobol14} are examples of programming languages that took an evolutionary approach, where modern language features are added and problems fixed within the framework of the existing language.
176Java~\cite{Java8}, Go~\cite{Go}, Rust~\cite{Rust} and D~\cite{D} are examples of the revolutionary approach for modernizing C/\CC, resulting in a new language rather than an extension of the descendent.
177These languages have different syntax and semantics from C, and do not interoperate directly with C, largely because of garbage collection.
178As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
179These costs can be prohibitive for many companies with a large software base in C/\CC, and many programmers that require retraining to a new programming language.
180
181The result of this project is a language that is largely backwards compatible with C11~\cite{C11}, but containing many modern language features and fixing some of the well known C problems.
182Without significant extension to the C programming language, C will be unable to cope with the needs of modern programming problems and programmers;
183as a result, it will fade into disuse.
184Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language.
185While C11 made a few simple extensions to the language, nothing was added to address existing problems in the language or to augment the language with modern language features.
186While some may argue that modern language features may make C complex and inefficient, it is clear a language without modern capabilities is insufficient for the advanced programming problems existing today.
187
188
189\section{Interoperability}
190
191\CFA is designed to integrate well with existing C programs and libraries.
192The most important feature of interoperability is to use the same calling conventions, so there is no overhead to call existing C routines.
193This feature allows users of \CFA to take advantage of the existing panoply of C libraries from inside their \CFA code.
194In fact, one of the biggest issues for any new programming language is establishing a minimum level of library code to support a large body of activities.
195Programming-language developers often state that adequate library support takes more work than designing and implementing the language itself.
196Like \CC, \CFA starts with immediate access to all exiting C libraries, and in many cases, can easily wrap library routines with simpler and safer interfaces, at very low cost.
197
198However, it is necessary to differentiate between C and \CFA code because of name overloading, as for \CC.
199For example, the C math-library provides the following routines for computing the absolute value of the basic type: \lstinline@abs@, \lstinline@labs@, \lstinline@llabs@, \lstinline@fabs@, \lstinline@fabsf@, \lstinline@fabsl@, \lstinline@cabsf@, \lstinline@cabs@, and \lstinline@cabsl@.
200Whereas, \CFA wraps each of these routines into one with the common name \lstinline@abs@.
201\begin{lstlisting}
202char abs( char );
203extern "C" {
204int abs( int );                         // use default C routine for int
205} // extern "C"
206long int abs( long int );
207long long int abs( long long int );
208float abs( float );
209double abs( double );
210long double abs( long double );
211float _Complex abs( float _Complex );
212double _Complex abs( double _Complex );
213long double _Complex abs( long double _Complex );
214\end{lstlisting}
215The problem is the name clash between the library routine \lstinline@abs@ and the \CFA names \lstinline@abs@.
216Hence, names appearing in an \lstinline@extern "C"@ block have \newterm{C linkage}.
217Then overloading polymorphism uses a mechanism called \newterm{name mangling} to create unique names that are different from C names, which are not mangled.
218Hence, there is the same need as in \CC, to know if a name is a C or \CFA name, so it can be correctly formed.
219There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type.
220This example strongly illustrates a core idea in \CFA: \emph{the power of a name}.
221The name ``\lstinline@abs@'' evokes the notion of absolute value, and many mathematical types provide the notion of absolute value.
222Hence, knowing the name \lstinline@abs@ should be sufficient to apply it to any type where it is applicable.
223The time savings and safety of using one name uniformly versus $N$ unique names should not be underestimated.
224
225
226\section{Compiling \CFA}
227
228The command \lstinline@cfa@ is used to compile \CFA program(s).
229This command works like the GNU \lstinline@gcc@\index{gcc} command, e.g.:
230\begin{lstlisting}
231cfa [ gcc-options ] C/@{\CFA}@-files [ assembler/loader-files ]
232\end{lstlisting}
233By default, \CFA programs having the following \lstinline@gcc@ flags turned on:
234\begin{description}
235\item
236\hspace*{-4pt}\lstinline@-std=gnu99@
237The 1999 C standard plus GNU extensions.
238\end{description}
239The following new \CFA option is available:
240\begin{description}
241\item
242\hspace*{-4pt}\lstinline@-CFA@
243Only the C preprocessor and the \CFA translator steps are performed and the transformed program is written to standard output, which makes it possible to examine the code generated by the \CFA translator.
244\end{description}
245
246
247\section{Underscores in Constants}
248
249Numeric constants are extended to allow \Index{underscore}s within constants\index{constant!underscore}, e.g.:
250\begin{lstlisting}
2512`_`147`_`483`_`648;                            // decimal constant
25256_ul;                                          // decimal unsigned long constant
2530_377;                                          // octal constant
2540x_ff_ff;                                       // hexadecimal constant
2550x_ef3d_aa5c;                           // hexadecimal constant
2563.141_592_654;                          // floating point constant
25710_e_+1_00;                                     // floating point constant
2580x_ff_ff_p_3;                           // hexadecimal floating point
2590x_1.ffff_ffff_p_128_l;         // hexadecimal floating point long constant
260L_"\x_ff_ee";                           // wide character constant
261\end{lstlisting}
262The rules for placement of underscores is as follows:
263\begin{enumerate}
264\item
265A sequence of underscores is disallowed, e.g., \lstinline@12__34@ is invalid.
266\item
267Underscores may only appear within a sequence of digits (regardless of the digit radix).
268In other words, an underscore cannot start or end a sequence of digits, e.g., \lstinline@_1@, \lstinline@1_@ and \lstinline@_1_@ are invalid (actually, the 1st and 3rd examples are identifier names).
269\item
270A numeric prefix may end with an underscore;
271a numeric infix may begin and/or end with an underscore;
272a numeric suffix may begin with an underscore.
273For example, the octal \lstinline@0@ or hexadecimal \lstinline@0x@ prefix may end with an underscore \lstinline@0_377@ or \lstinline@0x_ff@;
274the exponent infix \lstinline@E@ may start or end with an underscore \lstinline@1.0_E10@, \lstinline@1.0E_10@ or \lstinline@1.0_E_10@;
275the type suffixes \lstinline@U@, \lstinline@L@, etc. may start with an underscore \lstinline@1_U@, \lstinline@1_ll@ or \lstinline@1.0E10_f@.
276\end{enumerate}
277It is significantly easier to read and enter long constants when they are broken up into smaller groupings (most cultures use comma or period among digits for the same purpose).
278This extension is backwards compatible, matches with the use of underscore in variable names, and appears in Ada and Java.
279
280
281\section{Declarations}
282\label{s:Declarations}
283
284C declaration syntax is notoriously confusing and error prone.
285For example, many C programmers are confused by a declaration as simple as:
286\begin{lstlisting}
287int *x[ 10 ]
288\end{lstlisting}
289Is this a pointer to an array of 10 integers or an array of 10 pointers to integers?
290Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site.
291For example, a routine returning a pointer to an array of integers is defined and used in the following way:
292\begin{lstlisting}
293int (*f())[ 10 ] {...};
294... (*f())[  3 ] += 1;  // definition mimics usage
295\end{lstlisting}
296Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
297While attempting to make the two contexts consistent was a laudable goal, it has not worked out in practice.
298
299\CFA provides its own type, variable and routine declarations, using a slightly different syntax.
300The new declarations place modifiers to the left of the base type, while C declarations place modifiers to the right of the base type.
301The only exception is bit field specification, which always appear to the right of the base type.
302C and the new \CFA declarations may appear together in the same program block, but cannot be mixed within a specific declaration.
303
304In \CFA declarations, the same tokens are used as in C: the character \lstinline@*@ is used to indicate a pointer, square brackets \lstinline@[@\,\lstinline@]@ are used to represent an array, and parentheses \lstinline@()@ are used to indicate a routine parameter.
305However, unlike C, \CFA type declaration tokens are specified from left to right and the entire type specification is distributed across all variables in the declaration list.
306For instance, variables \lstinline@x@ and \lstinline@y@ of type pointer to integer are defined in \CFA as follows:
307\begin{quote2}
308\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
309\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
310\begin{lstlisting}
311`* int x, y;`
312\end{lstlisting}
313&
314\begin{lstlisting}
315int *x, *y;
316\end{lstlisting}
317\end{tabular}
318\end{quote2}
319Other examples are:
320\begin{quote2}
321\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
322\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
323\begin{lstlisting}
324[ 10 ] int z;
325[ 10 ] * char w;
326* [ 10 ] double v;
327struct s {
328        int f0:3;
329        * int f1;
330        [ 10 ] * int f2;
331};
332\end{lstlisting}
333&
334\begin{lstlisting}
335int z[ 10 ];
336char *w[ 10 ];
337double (*v)[ 10 ];
338struct s {
339        int f0:3;
340        int *f1;
341        int *f2[ 10 ]
342};
343\end{lstlisting}
344&
345\begin{lstlisting}
346// array of 10 integers
347// array of 10 pointers to char
348// pointer to array of 10 doubles
349
350// common bit field syntax
351
352
353
354\end{lstlisting}
355\end{tabular}
356\end{quote2}
357
358All type qualifiers, i.e., \lstinline@const@ and \lstinline@volatile@, are used in the normal way with the new declarations but appear left to right, e.g.:
359\begin{quote2}
360\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
361\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
362\begin{lstlisting}
363const * const int x;
364const * [ 10 ] const int y;
365\end{lstlisting}
366&
367\begin{lstlisting}
368int const * const x;
369const int (* const y)[ 10 ]
370\end{lstlisting}
371&
372\begin{lstlisting}
373// const pointer to const integer
374// const pointer to array of 10 const integers
375\end{lstlisting}
376\end{tabular}
377\end{quote2}
378All declaration qualifiers, i.e., \lstinline@extern@, \lstinline@static@, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier}
379The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}} e.g.:
380\begin{quote2}
381\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
382\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
383\begin{lstlisting}
384extern [ 10 ] int x;
385static * const int y;
386\end{lstlisting}
387&
388\begin{lstlisting}
389int extern x[ 10 ];
390const int static *y;
391\end{lstlisting}
392&
393\begin{lstlisting}
394// externally visible array of 10 integers
395// internally visible pointer to constant int
396\end{lstlisting}
397\end{tabular}
398\end{quote2}
399
400Unsupported are K\&R C declarations where the base type defaults to \lstinline@int@, if no type is specified\footnote{
401At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each structure declaration and type name~\cite[\S~6.7.2(2)]{C11}},
402e.g.:
403\begin{lstlisting}
404x;                                              // int x
405*y;                                             // int *y
406f( p1, p2 );                    // int f( int p1, int p2 );
407f( p1, p2 ) {}                  // int f( int p1, int p2 ) {}
408\end{lstlisting}
409
410As stated above, the two styles of declaration may appear together in the same block.
411Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
412Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems.
413
414
415\section{Type Operators}
416
417The new declaration syntax can be used in other contexts where types are required, e.g., casts and the pseudo-routine \lstinline@sizeof@:
418\begin{quote2}
419\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
420\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
421\begin{lstlisting}
422y = (* int)x;
423i = sizeof([ 10 ] * int);
424\end{lstlisting}
425&
426\begin{lstlisting}
427y = (int *)x;
428i = sizeof(int *[ 10 ]);
429\end{lstlisting}
430\end{tabular}
431\end{quote2}
432
433
434\section{Routine Definition}
435
436\CFA also supports a new syntax for routine definition, as well as ISO C and K\&R routine syntax.
437The point of the new syntax is to allow returning multiple values from a routine~\cite{CLU,Galletly96}, e.g.:
438\begin{lstlisting}
439`[ int o1, int o2, char o3 ]` f( int i1, char i2, char i3 ) {
440        @\emph{routine body}@
441}
442\end{lstlisting}
443where routine \lstinline@f@ has three output (return values) and three input parameters.
444Existing C syntax cannot be extended with multiple return types because it is impossible to embed a single routine name within multiple return type specifications.
445
446In detail, the brackets, \lstinline@[]@, enclose the result type, where each return value is named and that name is a local variable of the particular return type.\footnote{
447Michael Tiemann, with help from Doug Lea, provided named return values in g++, circa 1989.}
448The value of each local return variable is automatically returned at routine termination.
449Declaration qualifiers can only appear at the start of a routine definition, e.g.:
450\begin{lstlisting}
451extern [ int x ] g( int y ) {@\,@}
452\end{lstlisting}
453Lastly, if there are no output parameters or input parameters, the brackets and/or parentheses must still be specified;
454in both cases the type is assumed to be void as opposed to old style C defaults of int return type and unknown parameter types, respectively, as in:
455\begin{lstlisting}
456[@\,@] g(@\,@);                         // no input or output parameters
457[ void ] g( void );                     // no input or output parameters
458\end{lstlisting}
459
460Routine f is called as follows:
461\begin{lstlisting}
462[ i, j, ch ] = f( 3, 'a', ch );
463\end{lstlisting}
464The list of return values from f and the grouping on the left-hand side of the assignment is called a tuple and discussed in Section 12.
465
466\CFA style declarations cannot be used to declare parameters for K\&R style routine definitions because of the following ambiguity:
467\begin{lstlisting}
468int (*f(x))[ 10 ] int x; {}
469\end{lstlisting}
470The string ``\lstinline@int (*f(x))[ 10 ]@'' declares a K\&R style routine of type returning a pointer to an array of 10 integers, while the string ``\lstinline@[ 10 ] int x@'' declares a \CFA style parameter x of type array of 10 integers.
471Since the strings overlap starting with the open bracket, \lstinline@[@, there is an ambiguous interpretation for the string.
472As well, \CFA-style declarations cannot be used to declare parameters for C-style routine-definitions because of the following ambiguity:
473\begin{lstlisting}
474typedef int foo;
475int f( int (* foo) );           // foo is redefined as a parameter name
476\end{lstlisting}
477The string ``\lstinline@int (* foo)@'' declares a C-style named-parameter of type pointer to an integer (the parenthesis are superfluous), while the same string declares a \CFA style unnamed parameter of type routine returning integer with unnamed parameter of type pointer to foo.
478The redefinition of a type name in a parameter list is the only context in C where the character \lstinline@*@ can appear to the left of a type name, and \CFA relies on all type modifier characters appearing to the right of the type name.
479The inability to use \CFA declarations in these two contexts is probably a blessing because it precludes programmers from arbitrarily switching between declarations forms within a declaration contexts.
480
481C-style declarations can be used to declare parameters for \CFA style routine definitions, e.g.:
482\begin{lstlisting}
483[ int ] f( * int, int * );      // returns an integer, accepts 2 pointers to integers
484[ * int, int * ] f( int );      // returns 2 pointers to integers, accepts an integer
485\end{lstlisting}
486The reason for allowing both declaration styles in the new context is for backwards compatibility with existing preprocessor macros that generate C-style declaration-syntax, as in:
487\begin{lstlisting}
488#define ptoa( n, d ) int (*n)[ d ]
489int f( ptoa(p,10) ) ...         // expands to int f( int (*p)[ 10 ] )
490[ int ] f( ptoa(p,10) ) ...     // expands to [ int ] f( int (*p)[ 10 ] )
491\end{lstlisting}
492Again, programmers are highly encouraged to use one declaration form or the other, rather than mixing the forms.
493
494
495\subsection{Returning Values}
496
497Named return values handle the case where it is necessary to define a local variable whose value is then returned in a \lstinline@return@ statement, as in:
498\begin{lstlisting}
499int f() {
500        int x;
501        ... x = 0; ... x = y; ...
502        return x;
503}
504\end{lstlisting}
505Because the value in the return variable is automatically returned when a \CFA routine terminates, the \lstinline@return@ statement \emph{does not} contain an expression, as in:
506\begin{lstlisting}
507`[ int x ]` f() {
508        ... x = 0; ... x = y; ...
509        `return;` // implicitly return x
510}
511\end{lstlisting}
512When the return is encountered, the current value of \lstinline@x@ is returned to the calling routine.
513As well, ``falling off the end'' of a routine without a \lstinline@return@ statement is permitted, as in:
514\begin{lstlisting}
515[ int x ] f() {
516        ... x = 0; ... x = y; ...
517} // implicitly return x
518\end{lstlisting}
519In this case, the current value of \lstinline@x@ is returned to the calling routine just as if a \lstinline@return@ had been encountered.
520
521
522\subsection{Routine Prototype}
523
524The syntax of the new routine prototype declaration follows directly from the new routine definition syntax;
525as well, parameter names are optional, e.g.:
526\begin{lstlisting}
527[ int x ] f ();                         // returning int with no parameters
528[ * int ] g (int y);            // returning pointer to int with int parameter
529[ ] h (int,char);                       // returning no result with int and char parameters
530[ * int,int ] j (int);          // returning pointer to int and int, with int parameter
531\end{lstlisting}
532This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
533It is possible to declare multiple routine-prototypes in a single declaration, but the entire type specification is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), e.g.:
534\begin{quote2}
535\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
536\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
537\begin{lstlisting}
538[ int ] f(int), g;
539\end{lstlisting}
540&
541\begin{lstlisting}
542int f(int), g(int);
543\end{lstlisting}
544\end{tabular}
545\end{quote2}
546Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} e.g.:
547\begin{lstlisting}
548extern [ int ] f (int);
549static [ int ] g (int);
550\end{lstlisting}
551
552
553\section{Routine Pointers}
554
555The syntax for pointers to \CFA routines specifies the pointer name on the right, e.g.:
556\begin{lstlisting}
557* [ int x ] () fp;                      // pointer to routine returning int with no parameters
558* [ * int ] (int y) gp;         // pointer to routine returning pointer to int with int parameter
559* [ ] (int,char) hp;            // pointer to routine returning no result with int and char parameters
560* [ * int,int ] (int) jp;       // pointer to routine returning pointer to int and int, with int parameter
561\end{lstlisting}
562While parameter names are optional, \emph{a routine name cannot be specified};
563for example, the following is incorrect:
564\begin{lstlisting}
565* [ int x ] f () fp;            // routine name "f" is not allowed
566\end{lstlisting}
567
568
569\section{Named and Default Arguments}
570
571Named and default arguments~\cite{Hardgrave76}\footnote{
572Francez~\cite{Francez77} proposed a further extension to the named-parameter passing style, which specifies what type of communication (by value, by reference, by name) the argument is passed to the routine.}
573are two mechanisms to simplify routine call.
574Both mechanisms are discussed with respect to \CFA.
575\begin{description}
576\item[Named (or Keyword) Arguments:]
577provide the ability to specify an argument to a routine call using the parameter name rather than the position of the parameter.
578For example, given the routine:
579\begin{lstlisting}
580void p( int x, int y, int z ) {...}
581\end{lstlisting}
582a positional call is:
583\begin{lstlisting}
584p( 4, 7, 3 );
585\end{lstlisting}
586whereas a named (keyword) call may be:
587\begin{lstlisting}
588p( z : 3, x : 4, y : 7 ); // rewrite $\Rightarrow$ p( 4, 7, 3 )
589\end{lstlisting}
590Here the order of the arguments is unimportant, and the names of the parameters are used to associate argument values with the corresponding parameters.
591The compiler rewrites a named call into a positional call.
592The advantages of named parameters are:
593\begin{itemize}
594\item
595Remembering the names of the parameters may be easier than the order in the routine definition.
596\item
597Parameter names provide documentation at the call site (assuming the names are descriptive).
598\item
599Changes can be made to the order or number of parameters without affecting the call (although the call must still be recompiled).
600\end{itemize}
601
602Unfortunately, named arguments do not work in C-style programming-languages because a routine prototype is not required to specify parameter names, nor do the names in the prototype have to match with the actual definition.
603For example, the following routine prototypes and definition are all valid.
604\begin{lstlisting}
605void p( int, int, int );                        // equivalent prototypes
606void p( int x, int y, int z );
607void p( int y, int x, int z );
608void p( int z, int y, int x );
609void p( int q, int r, int s ) {}        // match with this definition
610\end{lstlisting}
611Forcing matching parameter names in routine prototypes with corresponding routine definitions is possible, but goes against a strong tradition in C programming.
612Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports.
613The former is easy to do, while the latter is more complex.
614Currently, \CFA does \emph{not} attempt to support named arguments.
615
616\item[Default Arguments]
617provide the ability to associate a default value with a parameter so it can be optionally specified in the argument list.
618For example, given the routine:
619\begin{lstlisting}
620void p( int x = 1, int y = 2, int z = 3 ) {...}
621\end{lstlisting}
622the allowable positional calls are:
623\begin{lstlisting}
624p();                            // rewrite $\Rightarrow$ p( 1, 2, 3 )
625p( 4 );                         // rewrite $\Rightarrow$ p( 4, 2, 3 )
626p( 4, 4 );                      // rewrite $\Rightarrow$ p( 4, 4, 3 )
627p( 4, 4, 4 );           // rewrite $\Rightarrow$ p( 4, 4, 4 )
628// empty arguments
629p(  , 4, 4 );           // rewrite $\Rightarrow$ p( 1, 4, 4 )
630p( 4,  , 4 );           // rewrite $\Rightarrow$ p( 4, 2, 4 )
631p( 4, 4,   );           // rewrite $\Rightarrow$ p( 4, 4, 3 )
632p( 4,  ,   );           // rewrite $\Rightarrow$ p( 4, 2, 3 )
633p(  , 4,   );           // rewrite $\Rightarrow$ p( 1, 4, 3 )
634p(  ,  , 4 );           // rewrite $\Rightarrow$ p( 1, 2, 4 )
635p(  ,  ,   );           // rewrite $\Rightarrow$ p( 1, 2, 3 )
636\end{lstlisting}
637Here the missing arguments are inserted from the default values in the parameter list.
638The compiler rewrites missing default values into explicit positional arguments.
639The advantages of default values are:
640\begin{itemize}
641\item
642Routines with a large number of parameters are often very generalized, giving a programmer a number of different options on how a computation is performed.
643For many of these kinds of routines, there are standard or default settings that work for the majority of computations.
644Without default values for parameters, a programmer is forced to specify these common values all the time, resulting in long argument lists that are error prone.
645\item
646When a routine's interface is augmented with new parameters, it extends the interface providing generalizability\footnote{
647``It should be possible for the implementor of an abstraction to increase its generality.
648So long as the modified abstraction is a generalization of the original, existing uses of the abstraction will not require change.
649It might be possible to modify an abstraction in a manner which is not a generalization without affecting existing uses, but, without inspecting the modules in which the uses occur, this possibility cannot be determined.
650This criterion precludes the addition of parameters, unless these parameters have default or inferred values that are valid for all possible existing applications.''~\cite[p.~128]{Cormack90}}
651(somewhat like the generalization provided by inheritance for classes).
652That is, all existing calls are still valid, although the call must still be recompiled.
653\end{itemize}
654The only disadvantage of default arguments is that unintentional omission of an argument may not result in a compiler-time error.
655Instead, a default value is used, which may not be the programmer's intent.
656
657Default values may only appear in a prototype versus definition context:
658\begin{lstlisting}
659void p( int x, int y = 2, int z = 3 );          // prototype: allowed
660void p( int, int = 2, int = 3 );                        // prototype: allowed
661void p( int x, int y = 2, int z = 3 ) {}        // definition: not allowed
662\end{lstlisting}
663The reason for this restriction is to allow separate compilation.
664Multiple prototypes with different default values is an error.
665\end{description}
666
667Ellipse (``...'') arguments present problems when used with default arguments.
668The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities:
669\begin{lstlisting}
670p( /* positional */, . . ., /* named */ );
671p( /* positional */, /* named */, . . . );
672\end{lstlisting}
673While it is possible to implement both approaches, the first possibly is more complex than the second, e.g.:
674\begin{lstlisting}
675p( int x, int y, int z, . . . );
676p( 1, 4, 5, 6, z : 3, y : 2 ); // assume p( /* positional */, . . ., /* named */ );
677p( 1, z : 3, y : 2, 4, 5, 6 ); // assume p( /* positional */, /* named */, . . . );
678\end{lstlisting}
679In the first call, it is necessary for the programmer to conceptually rewrite the call, changing named arguments into positional, before knowing where the ellipse arguments begin.
680Hence, this approach seems significantly more difficult, and hence, confusing and error prone.
681In the second call, the named arguments separate the positional and ellipse arguments, making it trivial to read the call.
682
683The problem is exacerbated with default arguments, e.g.:
684\begin{lstlisting}
685void p( int x, int y = 2, int z = 3. . . );
686p( 1, 4, 5, 6, z : 3 );         // assume p( /* positional */, . . ., /* named */ );
687p( 1, z : 3, 4, 5, 6 );         // assume p( /* positional */, /* named */, . . . );
688\end{lstlisting}
689The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments;
690therefore, argument 5 subsequently conflicts with the named argument z : 3.
691In the second call, the default value for y is implicitly inserted after argument 1 and the named arguments separate the positional and ellipse arguments, making it trivial to read the call.
692For these reasons, \CFA requires named arguments before ellipse arguments.
693Finally, while ellipse arguments are needed for a small set of existing C routines, like printf, the extended \CFA type system largely eliminates the need for ellipse arguments (see Section 24), making much of this discussion moot.
694
695Default arguments and overloading (see Section 24) are complementary.
696While in theory default arguments can be simulated with overloading, as in:
697\begin{quote2}
698\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
699\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{default arguments}}  & \multicolumn{1}{c}{\textbf{overloading}}      \\
700\begin{lstlisting}
701void p( int x, int y = 2, int z = 3 ) {...}
702
703
704\end{lstlisting}
705&
706\begin{lstlisting}
707void p( int x, int y, int z ) {...}
708void p( int x ) { p( x, 2, 3 ); }
709void p( int x, int y ) { p( x, y, 3 ); }
710\end{lstlisting}
711\end{tabular}
712\end{quote2}
713the number of required overloaded routines is linear in the number of default values, which is unacceptable growth.
714In general, overloading should only be used over default arguments if the body of the routine is significantly different.
715Furthermore, overloading cannot handle accessing default arguments in the middle of a positional list, via a missing argument, such as:
716\begin{lstlisting}
717p( 1, /* default */, 5 );               // rewrite $\Rightarrow$ p( 1, 2, 5 )
718\end{lstlisting}
719
720Given the \CFA restrictions above, both named and default arguments are backwards compatible.
721\CC only supports default arguments;
722Ada supports both named and default arguments.
723
724
725\section{Type/Routine Nesting}
726
727Nesting of types and routines is useful for controlling name visibility (\newterm{name hiding}).
728
729
730\subsection{Type Nesting}
731
732\CFA allows \Index{type nesting}, and type qualification of the nested types, where as C hoists\index{type!hoisting} (refactors) nested types into the enclosing scope and has no type qualification.
733\begin{quote2}
734\begin{tabular}{@{}l@{\hspace{30pt}}l|l@{}}
735\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{C Type Nesting}}     & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}}      & \multicolumn{1}{|c}{\textbf{\CFA}}    \\
736\hline
737\begin{lstlisting}
738struct S {
739        enum C { R, G, B };
740        struct T {
741                union U { int i, j; };
742                enum C c;
743                short int i, j;
744        };
745        struct T t;
746} s;
747
748int fred() {
749        s.t.c = R;
750        struct T t = { R, 1, 2 };
751        enum C c;
752        union U u;
753}
754\end{lstlisting}
755&
756\begin{lstlisting}
757enum C { R, G, B };
758union U { int i, j; };
759struct T {
760        enum C c;
761        short int i, j;
762};
763struct S {
764        struct T t;
765} s;
766       
767
768
769
770
771
772
773\end{lstlisting}
774&
775\begin{lstlisting}
776struct S {
777        enum C { R, G, B };
778        struct T {
779                union U { int i, j; };
780                enum C c;
781                short int i, j;
782        };
783        struct T t;
784} s;
785
786int fred() {
787        s.t.c = `S.`R;  // type qualification
788        struct `S.`T t = { `S.`R, 1, 2 };
789        enum `S.`C c;
790        union `S.T.`U u;
791}
792\end{lstlisting}
793\end{tabular}
794\end{quote2}
795In the left example in C, types \lstinline@C@, \lstinline@U@ and \lstinline@T@ are implicitly hoisted outside of type \lstinline@S@ into the containing block scope.
796In the right example in \CFA, the types are not hoisted and accessed using the field-selection operator ``\lstinline@.@'' for type qualification, as does Java, rather than the \CC type-selection operator ``\lstinline@::@''.
797
798
799\subsection{Routine Nesting}
800
801While \CFA does not provide object programming by putting routines into structures, it does rely heavily on locally nested routines to redefine operations at or close to a call site.
802For example, the C quick-sort is wrapped into the following polymorphic \CFA routine:
803\begin{lstlisting}
804forall( otype T | { int ?<?( T, T ); } )
805void qsort( const T * arr, size_t dimension );
806\end{lstlisting}
807which can be used to sort in ascending and descending order by locally redefining the less-than operator into greater-than.
808\begin{lstlisting}
809const unsigned int size = 10;
810int ia[size];
811...                                             // assign values to array ia
812qsort( ia, size );              // sort ascending order using builtin ?<?
813{
814        `int ?<?( int x, int y ) { return x > y; }` // nested routine
815        qsort( ia, size );      // sort descending order by local redefinition
816}
817\end{lstlisting}
818
819Nested routines are not first-class, meaning a nested routine cannot be returned if it has references to variables in its enclosing blocks;
820the only exception is references to the external block of the translation unit, as these variables persist for the duration of the program.
821The following program in undefined in \CFA (and \lstinline@gcc@\index{gcc})
822\begin{lstlisting}
823[* [int]( int )] foo() {                // int (*foo())( int )
824        int `i` = 7;
825        int bar( int p ) {
826                `i` += 1;                                       // dependent on local variable
827                sout | `i` | endl;
828        }
829        return bar;                                     // undefined because of local dependence
830}
831int main() {
832        * [int](int) fp = foo();        // int (*fp)(int)
833    sout | fp( 3 ) | endl;
834}
835\end{lstlisting}
836because
837
838Currently, there are no \Index{lambda} expressions, i.e., unnamed routines because routine names are very important to properly select the correct routine.
839
840
841\section{Tuples}
842
843In C and \CFA, lists of elements appear in several contexts, such as the parameter list for a routine call.
844(More contexts are added shortly.)
845A list of such elements is called a tuple.
846The general syntax of a tuple is:
847\begin{lstlisting}
848[ $\emph{exprlist}$ ]
849\end{lstlisting}
850where \lstinline@$\emph{exprlist}$@ is a list of one or more expressions separated by commas.
851The brackets, \lstinline$[]$, allow differentiating between tuples and expressions containing the C comma operator.
852The following are examples of tuples:
853\begin{lstlisting}
854[ x, y, z ]
855[ 2 ]
856[ v+w, x*y, 3.14159, f() ]
857\end{lstlisting}
858Tuples are permitted to contain sub-tuples (i.e., nesting), such as \lstinline@[ [ 14, 21 ], 9 ]@, which is a 2-element tuple whose first element is itself a tuple.
859Note, a tuple is not a record (structure);
860a record denotes a single value with substructure, whereas a tuple is multiple values with no substructure (see flattening coercion in Section 12.1).
861In essence, tuples are largely a compile time phenomenon, having little or no runtime presence.
862
863Tuples can be organized into compile-time tuple variables;
864these variables are of \newterm{tuple type}.
865Tuple variables and types can be used anywhere lists of conventional variables and types can be used.
866The general syntax of a tuple type is:
867\begin{lstlisting}
868[ @\emph{typelist}@ ]
869\end{lstlisting}
870where \lstinline@$\emph{typelist}$@ is a list of one or more legal \CFA or C type specifications separated by commas, which may include other tuple type specifications.
871Examples of tuple types include:
872\begin{lstlisting}
873[ unsigned int, char ]
874[ double, double, double ]
875[ * int, int * ]                // mix of CFA and ANSI
876[ * [ 10 ] int, * * char, * [ [ int, int ] ] (int, int) ]
877\end{lstlisting}
878Like tuples, tuple types may be nested, such as \lstinline@[ [ int, int ], int ]@, which is a 2-element tuple type whose first element is itself a tuple type.
879
880Examples of declarations using tuple types are:
881\begin{lstlisting}
882[ int, int ] x;                 // 2 element tuple, each element of type int
883* [ char, char ] y;             // pointer to a 2 element tuple
884[ [ int, int ] ] z ([ int, int ]);
885\end{lstlisting}
886The last example declares an external routine that expects a 2 element tuple as an input parameter and returns a 2 element tuple as its result.
887
888As mentioned, tuples can appear in contexts requiring a list of value, such as an argument list of a routine call.
889In unambiguous situations, the tuple brackets may be omitted, e.g., a tuple that appears as an argument may have its
890square brackets omitted for convenience; therefore, the following routine invocations are equivalent:
891\begin{lstlisting}
892f( [ 1, x+2, fred() ] );
893f( 1, x+2, fred() );
894\end{lstlisting}
895Also, a tuple or a tuple variable may be used to supply all or part of an argument list for a routine expecting multiple input parameters or for a routine expecting a tuple as an input parameter.
896For example, the following are all legal:
897\begin{lstlisting}
898[ int, int ] w1;
899[ int, int, int ] w2;
900[ void ] f (int, int, int); /* three input parameters of type int */
901[ void ] g ([ int, int, int ]); /* 3 element tuple as input */
902f( [ 1, 2, 3 ] );
903f( w1, 3 );
904f( 1, w1 );
905f( w2 );
906g( [ 1, 2, 3 ] );
907g( w1, 3 );
908g( 1, w1 );
909g( w2 );
910\end{lstlisting}
911Note, in all cases 3 arguments are supplied even though the syntax may appear to supply less than 3. As mentioned, a
912tuple does not have structure like a record; a tuple is simply converted into a list of components.
913\begin{rationale}
914The present implementation of \CFA does not support nested routine calls when the inner routine returns multiple values; i.e., a statement such as \lstinline@g( f() )@ is not supported.
915Using a temporary variable to store the  results of the inner routine and then passing this variable to the outer routine works, however.
916\end{rationale}
917
918A tuple can contain a C comma expression, provided the expression containing the comma operator is enclosed in parentheses.
919For instance, the following tuples are equivalent:
920\begin{lstlisting}
921[ 1, 3, 5 ]
922[ 1, (2, 3), 5 ]
923\end{lstlisting}
924The second element of the second tuple is the expression (2, 3), which yields the result 3.
925This requirement is the same as for comma expressions in argument lists.
926
927Type qualifiers, i.e., const and volatile, may modify a tuple type.
928The meaning is the same as for a type qualifier modifying an aggregate type [Int99, x 6.5.2.3(7),x 6.7.3(11)], i.e., the qualifier is distributed across all of the types in the tuple, e.g.:
929\begin{lstlisting}
930const volatile [ int, float, const int ] x;
931\end{lstlisting}
932is equivalent to:
933\begin{lstlisting}
934[ const volatile int, const volatile float, const volatile int ] x;
935\end{lstlisting}
936Declaration qualifiers can only appear at the start of a \CFA tuple declaration4, e.g.:
937\begin{lstlisting}
938extern [ int, int ] w1;
939static [ int, int, int ] w2;
940\end{lstlisting}
941\begin{rationale}
942Unfortunately, C's syntax for subscripts precluded treating them as tuples.
943The C subscript list has the form \lstinline@[i][j]...@ and not \lstinline@i, j, ...]@.
944Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, e.g., \lstinline@f[g()]@ always means a single subscript value because there is only one set of brackets.
945Fixing this requires a major change to C because the syntactic form \lstinline@M[i, j, k]@ already has a particular meaning: \lstinline@i, j, k@ is a comma expression.
946\end{rationale}
947
948
949\subsection{Tuple Coercions}
950
951There are four coercions that can be performed on tuples and tuple variables: closing, opening, flattening and structuring.
952In addition, the coercion of dereferencing can be performed on a tuple variable to yield its value(s), as for other variables.
953A \newterm{closing coercion} takes a set of values and converts it into a tuple value, which is a contiguous set of values, as in:
954\begin{lstlisting}
955[ int, int, int, int ] w;
956w = [ 1, 2, 3, 4 ];
957\end{lstlisting}
958First the right-hand tuple is closed into a tuple value and then the tuple value is assigned.
959
960An \newterm{opening coercion} is the opposite of closing; a tuple value is converted into a tuple of values, as in:
961\begin{lstlisting}
962[ a, b, c, d ] = w
963\end{lstlisting}
964\lstinline@w@ is implicitly opened to yield a tuple of four values, which are then assigned individually.
965
966A \newterm{flattening coercion} coerces a nested tuple, i.e., a tuple with one or more components, which are themselves tuples, into a flattened tuple, which is a tuple whose components are not tuples, as in:
967\begin{lstlisting}
968[ a, b, c, d ] = [ 1, [ 2, 3 ], 4 ];
969\end{lstlisting}
970First the right-hand tuple is flattened and then the values are assigned individually.
971Flattening is also performed on tuple types.
972For example, the type \lstinline@[ int, [ int, int ], int ]@ can be coerced, using flattening, into the type \lstinline@[ int, int, int, int ]@.
973
974A \newterm{structuring coercion} is the opposite of flattening;
975a tuple is structured into a more complex nested tuple.
976For example, structuring the tuple \lstinline@[ 1, 2, 3, 4 ]@ into the tuple \lstinline@[ 1, [ 2, 3 ], 4 ]@ or the tuple type \lstinline@[ int, int, int, int ]@ into the tuple type \lstinline@[ int, [ int, int ], int ]@.
977In the following example, the last assignment illustrates all the tuple coercions:
978\begin{lstlisting}
979[ int, int, int, int ] w = [ 1, 2, 3, 4 ];
980int x = 5;
981[ x, w ] = [ w, x ];            // all four tuple coercions
982\end{lstlisting}
983Starting on the right-hand tuple in the last assignment statement, w is opened, producing a tuple of four values;
984therefore, the right-hand tuple is now the tuple \lstinline@[ [ 1, 2, 3, 4 ], 5 ]@.
985This tuple is then flattened, yielding \lstinline@[ 1, 2, 3, 4, 5 ]@, which is structured into \lstinline@[ 1, [ 2, 3, 4, 5 ] ]@ to match the tuple type of the left-hand side.
986The tuple \lstinline@[ 2, 3, 4, 5 ]@ is then closed to create a tuple value.
987Finally, \lstinline@x@ is assigned \lstinline@1@ and \lstinline@w@ is assigned the tuple value using multiple assignment (see Section 14).
988\begin{rationale}
989A possible additional language extension is to use the structuring coercion for tuples to initialize a complex record with a tuple.
990\end{rationale}
991
992
993\section{Mass Assignment}
994
995\CFA permits assignment to several variables at once using mass assignment~\cite{CLU}.
996Mass assignment has the following form:
997\begin{lstlisting}
998[ @\emph{lvalue}@, ..., @\emph{lvalue}@ ] = @\emph{expr}@;
999\end{lstlisting}
1000The left-hand side is a tuple of \lstinline@$\emph{lvalues}$@, which is a list of expressions each yielding an address, i.e., any data object that can appear on the left-hand side of a conventional assignment statement.
1001\lstinline@$\emph{expr}$@ is any standard arithmetic expression.
1002Clearly, the types of the entities being assigned must be type compatible with the value of the expression.
1003
1004Mass assignment has parallel semantics, e.g., the statement:
1005\begin{lstlisting}
1006[ x, y, z ] = 1.5;
1007\end{lstlisting}
1008is equivalent to:
1009\begin{lstlisting}
1010x = 1.5; y = 1.5; z = 1.5;
1011\end{lstlisting}
1012This semantics is not the same as the following in C:
1013\begin{lstlisting}
1014x = y = z = 1.5;
1015\end{lstlisting}
1016as conversions between intermediate assignments may lose information.
1017A more complex example is:
1018\begin{lstlisting}
1019[ i, y[i], z ] = a + b;
1020\end{lstlisting}
1021which is equivalent to:
1022\begin{lstlisting}
1023t = a + b;
1024a1 = &i; a2 = &y[i]; a3 = &z;
1025*a1 = t; *a2 = t; *a3 = t;
1026\end{lstlisting}
1027The temporary \lstinline@t@ is necessary to store the value of the expression to eliminate conversion issues.
1028The temporaries for the addresses are needed so that locations on the left-hand side do not change as the values are assigned.
1029In this case, \lstinline@y[i]@ uses the previous value of \lstinline@i@ and not the new value set at the beginning of the mass assignment.
1030
1031
1032\section{Multiple Assignment}
1033
1034\CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}.
1035Multiple assignment has the following form:
1036\begin{lstlisting}
1037[ @\emph{lvalue}@, . . ., @\emph{lvalue}@ ] = [ @\emph{expr}@, . . ., @\emph{expr}@ ];
1038\end{lstlisting}
1039The left-hand side is a tuple of \lstinline@$\emph{lvalues}$@, and the right-hand side is a tuple of \lstinline@$\emph{expr}$@s.
1040Each \lstinline@$\emph{expr}$@ appearing on the righthand side of a multiple assignment statement is assigned to the corresponding \lstinline@$\emph{lvalues}$@ on the left-hand side of the statement using parallel semantics for each assignment.
1041An example of multiple assignment is:
1042\begin{lstlisting}
1043[ x, y, z ] = [ 1, 2, 3 ];
1044\end{lstlisting}
1045Here, the values \lstinline@1@, \lstinline@2@ and \lstinline@3@ are assigned, respectively, to the variables \lstinline@x@, \lstinline@y@ and \lstinline@z@.
1046 A more complex example is:
1047\begin{lstlisting}
1048[ i, y[ i ], z ] = [ 1, i, a + b ];
1049\end{lstlisting}
1050Here, the values \lstinline@1@, \lstinline@i@ and \lstinline@a + b@ are assigned to the variables \lstinline@i@, \lstinline@y[i]@ and \lstinline@z@, respectively.
1051 Note, the parallel semantics of
1052multiple assignment ensures:
1053\begin{lstlisting}
1054[ x, y ] = [ y, x ];
1055\end{lstlisting}
1056correctly interchanges (swaps) the values stored in \lstinline@x@ and \lstinline@y@.
1057The following cases are errors:
1058\begin{lstlisting}
1059[ a, b, c ] = [ 1, 2, 3, 4 ];
1060[ a, b, c ] = [ 1, 2 ];
1061\end{lstlisting}
1062because the number of entities in the left-hand tuple is unequal with the right-hand tuple.
1063
1064As for all tuple contexts in C, side effects should not be used because C does not define an ordering for the evaluation of the elements of a tuple;
1065both these examples produce indeterminate results:
1066\begin{lstlisting}
1067f( x++, x++ );                          // C routine call with side effects in arguments
1068[ v1, v2 ] = [ x++, x++ ];      // side effects in righthand side of multiple assignment
1069\end{lstlisting}
1070
1071
1072\section{Cascade Assignment}
1073
1074As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment.
1075Cascade assignment has the following form:
1076\begin{lstlisting}
1077@\emph{tuple}@ = @\emph{tuple}@ = ... = @\emph{tuple}@;
1078\end{lstlisting}
1079and it has the same parallel semantics as for mass and multiple assignment.
1080Some examples of cascade assignment are:
1081\begin{lstlisting}
1082x1 = y1 = x2 = y2 = 0;
1083[ x1, y1 ] = [ x2, y2 ] = [ x3, y3 ];
1084[ x1, y1 ] = [ x2, y2 ] = 0;
1085[ x1, y1 ] = z = 0;
1086\end{lstlisting}
1087As in C, the rightmost assignment is performed first, i.e., assignment parses right to left.
1088
1089
1090\section{Field Tuples}
1091
1092Tuples may be used to select multiple fields of a record by field name.
1093Its general form is:
1094\begin{lstlisting}
1095@\emph{expr}@ . [ @\emph{fieldlist}@ ]
1096@\emph{expr}@ -> [ @\emph{fieldlist}@ ]
1097\end{lstlisting}
1098\lstinline@$\emph{expr}$@ is any expression yielding a value of type record, e.g., \lstinline@struct@, \lstinline@union@.
1099Each element of \lstinline@$\emph{ fieldlist}$@ is an element of the record specified by \lstinline@$\emph{expr}$@.
1100A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is
1101the following:
1102\begin{lstlisting}
1103struct s {
1104        int f1, f2;
1105        char f3;
1106        double f4;
1107} v;
1108v.[ f3, f1, f2 ] = ['x', 11, 17 ];      // equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17
1109f( v.[ f3, f1, f2 ] );                          // equivalent to f( v.f3, v.f1, v.f2 )
1110\end{lstlisting}
1111Note, the fields appearing in a record-field tuple may be specified in any order;
1112also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple.
1113
1114If a field of a \lstinline@struct@ is itself another \lstinline@struct@, multiple fields of this subrecord can be specified using a nested record-field tuple, as in the following example:
1115\begin{lstlisting}
1116struct inner {
1117        int f2, f3;
1118};
1119struct outer {
1120        int f1;
1121        struct inner i;
1122        double f4;
1123} o;
1124
1125o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ];
1126\end{lstlisting}
1127
1128
1129\section{Labelled Break/Continue}
1130
1131While C provides \lstinline@break@ and \lstinline@continue@ statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
1132Unfortunately, this restriction forces programmers to use \lstinline@goto@ to achieve the equivalent for more than one level of nesting.
1133To prevent having to make this switch, the \lstinline@break@ and \lstinline@continue@ are extended with a target label to support static multi-level exit~\cite{Buhr85,Java}.
1134For the labelled \lstinline@break@, it is possible to specify which control structure is the target for exit, as in:
1135\begin{quote2}
1136\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
1137\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
1138\begin{lstlisting}
1139`L1:` for ( ... ) {
1140        `L2:` for ( ... ) {
1141                `L3:` for ( ... ) {
1142                        ... break `L1`; ...
1143                        ... break `L2`; ...
1144                        ... break `L3`; // or break
1145                }
1146        }
1147}
1148\end{lstlisting}
1149&
1150\begin{lstlisting}
1151for ( ... ) {
1152        for ( ... ) {
1153                for ( ... ) {
1154                        ... goto L1; ...
1155                        ... goto L2; ...
1156                        ... goto L3; // or break
1157                } L3: ;
1158        } L2: ;
1159} L1: ;
1160\end{lstlisting}
1161\end{tabular}
1162\end{quote2}
1163The inner most loop has three exit points, which cause termination of one or more of the three nested loops, respectively.
1164For the labelled \lstinline@continue@, it is possible to specify which control structure is the target for the next loop iteration, as in:
1165\begin{quote2}
1166\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
1167\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
1168\begin{lstlisting}
1169`L1`: for ( ... ) {
1170        `L2`: for ( ... ) {
1171                `L3`: for ( ... ) {
1172                        ... continue `L1`; ...
1173                        ... continue `L2`; ...
1174                        ... continue `L3`; ...
1175
1176                }
1177
1178        }
1179
1180}
1181\end{lstlisting}
1182&
1183\begin{lstlisting}
1184for ( ... ) {
1185        for ( ... ) {
1186                for ( ... ) {
1187                        ... goto L1; ...
1188                        ... goto L2; ...
1189                        ... goto L3; ...
1190                  L3: ;
1191                }
1192          L2: ;
1193        }
1194  L1: ;
1195}
1196\end{lstlisting}
1197\end{tabular}
1198\end{quote2}
1199The inner most loop has three restart points, which cause the next loop iteration to begin, respectively.
1200For both \lstinline@break@ and \lstinline@continue@, the target label must be directly associated with a \lstinline@for@, \lstinline@while@ or \lstinline@do@ statement;
1201for \lstinline@break@, the target label can also be associated with a \lstinline@switch@ statement.
1202Both \lstinline@break@ and \lstinline@continue@ with target labels are simply a \lstinline@goto@ restricted in the following ways:
1203\begin{itemize}
1204\item
1205They cannot be used to create a loop.
1206This means that only the looping construct can be used to create a loop.
1207This restriction is important since all situations that can result in repeated execution of statements in a program are clearly delineated.
1208\item
1209Since they always transfers out of containing control structures, they cannot be used to branch into a control structure.
1210\end{itemize}
1211The advantage of the labelled \lstinline@break@/\lstinline@continue@ is that it allows static multi-level exits without having to use the \lstinline@goto@ statement and ties control flow to the target control structure rather than an arbitrary point in a program.
1212Furthermore, the location of the label at the beginning of the target control structure informs the reader that complex control-flow is occurring in the body of the control structure.
1213With \lstinline@goto@, the label at the end of the control structure fails to convey this important clue early enough to the reader.
1214Finally, using an explicit target for the transfer instead of an implicit target allows new nested loop or switch constructs to be added or removed without affecting other constructs.
1215The implicit targets of the current \lstinline@break@ and \lstinline@continue@, i.e., the closest enclosing loop or \lstinline@switch@, change as certain constructs are added or removed.
1216
1217
1218\section{Switch Statement}
1219
1220C allows a number of questionable forms for the \lstinline@switch@ statement:
1221\begin{enumerate}
1222\item
1223By default, the end of a \lstinline@case@ clause\footnote{
1224In this section, the term \emph{case clause} refers to either a \lstinline@case@ or \lstinline@default@ clause.}
1225\emph{falls through} to the next \lstinline@case@ clause in the \lstinline@switch@ statement;
1226to exit a \lstinline@switch@ statement from a \lstinline@case@ clause requires explicitly terminating the clause with a transfer statement, most commonly \lstinline@break@, as in:
1227\begin{lstlisting}
1228switch ( i ) {
1229  case 1:
1230        ...
1231        // fall-through
1232  case 2:
1233        ...
1234        break;  // exit switch statement
1235}
1236\end{lstlisting}
1237The ability to fall-through to the next clause is a useful form of control flow, specifically when a sequence of case actions compound, as in:
1238\begin{lstlisting}
1239switch ( argc ) {
1240  case 3:
1241        // open output file
1242        // fall-through
1243  case 2:
1244        // open input file
1245        break;  // exit switch statement
1246  default:
1247        // usage message
1248}
1249\end{lstlisting}
1250In this example, case 2 is always done if case 3 is done.
1251This control flow is difficult to simulate with if statements or a \lstinline@switch@ statement without fall-through as code must be duplicated or placed in a separate routine.
1252C also uses fall-through to handle multiple case-values resulting in the same action, as in:
1253\begin{lstlisting}
1254switch ( i ) {
1255  case 1: case 3: case 5:       // odd values
1256        // same action
1257        break;
1258  case 2: case 4: case 6:       // even values
1259        // same action
1260        break;
1261}
1262\end{lstlisting}
1263However, this situation is handled in other languages without fall-through by allowing a list of case values.
1264While fall-through itself is not a problem, the problem occurs when fall-through is the \lstinline@default@, as this semantics is not intuitive to most programmers and is different from virtually all other programming languages with a \lstinline@switch@ statement.
1265Hence, \lstinline@default@ fall-through semantics results in a large number of programming errors as programmers often forget the \lstinline@break@ statement at the end of a \lstinline@case@ clause, resulting in inadvertent fall-through.
1266
1267\item
1268It is possible to place \lstinline@case@ clauses on statements nested \emph{within} the body of the \lstinline@switch@ statement, as in:
1269\begin{lstlisting}
1270switch ( i ) {
1271  case 0:
1272        if ( j < k ) {
1273                ...
1274          case 1:               // transfer into "if" statement
1275                if ( j < m ) {
1276                        ...
1277                  case 2:       // transfer into "if" statement
1278                        ...
1279                }
1280        }
1281  case 3:
1282        while ( j < 5 ) {
1283                ...
1284          case 4:               // transfer into "while" statement
1285                ...
1286        }
1287}
1288\end{lstlisting}
1289The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties.
1290The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it.
1291The technical problem results from the inability to ensure allocation and initialization of variables when blocks are not entered at the beginning.
1292Often transferring into a block can bypass variable declaration and/or its initialization, which results in subsequent errors.
1293There are virtually no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it.
1294Nevertheless, C does have an idiom where this capability is used, known as ``Duff's device''~\cite{Duff83}:
1295\begin{lstlisting}
1296register int n = (count + 7) / 8;
1297switch ( count % 8 ) {
1298case 0: do{ *to = *from++;
1299case 7:         *to = *from++;
1300case 6:         *to = *from++;
1301case 5:         *to = *from++;
1302case 4:         *to = *from++;
1303case 3:         *to = *from++;
1304case 2:         *to = *from++;
1305case 1:         *to = *from++;
1306                } while ( --n > 0 );
1307}
1308\end{lstlisting}
1309which unrolls a loop N times (N = 8 above) and uses the \lstinline@switch@ statement to deal with any iterations not a multiple of N.
1310While efficient, this sort of special purpose usage is questionable:
1311\begin{quote}
1312Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this
1313discovery.~\cite{Duff83}
1314\end{quote}
1315\item
1316It is possible to place the \lstinline@default@ clause anywhere in the list of labelled clauses for a \lstinline@switch@ statement, rather than only at the end.
1317Virtually all programming languages with a \lstinline@switch@ statement require the \lstinline@default@ clause to appear last in the case-clause list.
1318The logic for this semantics is that after checking all the \lstinline@case@ clauses without success, the \lstinline@default@ clause is selected;
1319hence, physically placing the \lstinline@default@ clause at the end of the \lstinline@case@ clause list matches with this semantics.
1320This physical placement can be compared to the physical placement of an \lstinline@else@ clause at the end of a series of connected \lstinline@if@/\lstinline@else@ statements.
1321
1322\item
1323It is possible to place unreachable code at the start of a \lstinline@switch@ statement, as in:
1324\begin{lstlisting}
1325switch ( x ) {
1326        int y = 1;                      // unreachable initialization
1327        x = 7;                          // unreachable code
1328  case 3: ...
1329        y = 3;
1330        ...
1331}
1332\end{lstlisting}
1333While the declaration of the local variable \lstinline@y@ is useful and its scope is across all \lstinline@case@ clauses, the initialization for such a variable is defined to never be executed because control always transfers over it.
1334Furthermore, any statements before the first \lstinline@case@ clause can only be executed if labelled and transfered to using a \lstinline@goto@, either from outside or inside of the \lstinline@switch@.
1335As mentioned, transfer into control structures should be forbidden.
1336Transfers from within the \lstinline@switch@ body using a \lstinline@goto@ are equally unpalatable.
1337\end{enumerate}
1338Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program:
1339\begin{itemize}
1340\item
1341the number of \lstinline@switch@ statements is small,
1342\item
1343most \lstinline@switch@ statements are well formed (i.e., no Duff's device),
1344\item
1345the \lstinline@default@ clause is usually written as the last case-clause,
1346\item
1347and there is only a medium amount of fall-through from one \lstinline@case@ clause to the next, and most of these result from a list of case values executing common code, rather than a sequence of case actions that compound.
1348\end{itemize}
1349These observations should help to put the effects of suggested changes into perspective.
1350% Figure 1 shows the grammar change that attempts to minimize the effect on existing C programs.
1351\begin{enumerate}
1352\item
1353Eliminating the \lstinline@default@ fall-through problem has the greatest potential for affecting existing code.
1354However, even if fall-through is removed, most \lstinline@switch@ statements would continue to work because of the explicit transfers already present at the end of each \lstinline@case@ clause, and the common placement of the \lstinline@default@ clause at the end of the case list.
1355In addition, the above grammar provides for the most common use of fall-through, i.e., a list of \lstinline@case@ clauses executing common code, e.g.:
1356\begin{lstlisting}
1357case 1:  case 2:  case 3: ...
1358\end{lstlisting}
1359Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments.
1360Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of \lstinline@switch@ statement, called \lstinline@choose@, with no fall-through semantics.
1361The \lstinline@choose@ statement is identical to the new \lstinline@switch@ statement, except there is no implicit fall-through between case-clauses and the \lstinline@break@ statement applies to the enclosing loop construct (as for the continue statement in a \lstinline@switch@ statement).
1362It is still possible to fall-through if a case-clause ends with the new keyword fallthru, e.g.:
1363\begin{lstlisting}
1364choose ( i ) {
1365        int i;
1366  case 3, 4:
1367        i = 3;
1368        fallthru;
1369  case 8, 10:
1370  default:
1371        j = 3;
1372}
1373\end{lstlisting}
1374The ability to fall-through is retained because it is a sufficient C-idiom that most C programmers simply expect it, and its absence might discourage these programmers from using the choose statement.
1375\item
1376Eliminating Duff's device is straightforward and only invalidates a small amount of very questionable code.
1377The solution is to allow \lstinline@case@ clauses to only appear at the same nesting level as the \lstinline@switch@ body, as is done in most other programming languages with \lstinline@switch@ statements.
1378\item
1379The issue of \lstinline@default@ at locations other than at the end of the cause clause can be solved by using good programming style, and there are a few reasonable situations involving fall-through where the \lstinline@default@ clause may appear is locations other than at the end.
1380Therefore, no language change is made for this issue.
1381\item
1382Dealing with unreachable code at the start of a \lstinline@switch@ statement is solved by defining the declaration-list, including any associated initialization, at the start of a \lstinline@switch@ statement body to be executed before the transfer to the appropriate \lstinline@case@ clause.
1383This semantics is the same as for declarations at the start of a loop body, which are executed before each iteration of the loop body.
1384As well, this grammar does not allow statements to appear before the first \lstinline@case@ clause.
1385The change is compatible for declarations with initialization in this context because existing code cannot assume the initialization has occurred.
1386The change is incompatible for statements, but any existing code using it is highly questionable, as in:
1387\begin{lstlisting}
1388switch ( i ) {
1389        L: x = 5;               // questionable code
1390  case 0:
1391        ...
1392}
1393\end{lstlisting}
1394The statement after the \lstinline@switch@ can never be executed unless it is labelled.
1395If it is labelled, it must be transfered to from outside or inside the \lstinline@switch@ statement, neither of which is acceptable control flow.
1396\end{enumerate}
1397
1398
1399\section{Case Clause}
1400
1401C restricts the \lstinline@case@ clause of a \lstinline@switch@ statement to a single value.
1402For multiple \lstinline@case@ clauses associated with the same statement, it is necessary to have multiple \lstinline@case@ clauses rather than multiple values.
1403Requiring a \lstinline@case@ clause for each value does not seem to be in the spirit of brevity normally associated with C.
1404Therefore, the \lstinline@case@ clause is extended with a list of values, as in:
1405\begin{quote2}
1406\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
1407\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
1408\begin{lstlisting}
1409switch ( i ) {
1410  `case 1, 3, 5`:
1411        ...
1412  `case 2, 4, 6`:
1413        ...
1414}
1415\end{lstlisting}
1416&
1417\begin{lstlisting}
1418switch ( i ) {
1419  case 1: case 3 : case 5:
1420        ...
1421  case 2: case 4 : case 6:
1422        ...
1423}
1424\end{lstlisting}
1425&
1426\begin{lstlisting}
1427
1428// odd values
1429
1430// even values
1431
1432
1433\end{lstlisting}
1434\end{tabular}
1435\end{quote2}
1436In addition, two forms of subranges are allowed to specify case values: the GNU C form and a new \CFA form.
1437\begin{quote2}
1438\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
1439\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{GNU C}}    \\
1440\begin{lstlisting}
1441switch ( i ) {
1442  `case 1~5:`
1443        ...
1444  `case 10~15:`
1445        ...
1446}
1447\end{lstlisting}
1448&
1449\begin{lstlisting}
1450switch ( i )
1451  case 1 ... 5:
1452        ...
1453  case 10 ... 15:
1454        ...
1455}
1456\end{lstlisting}
1457&
1458\begin{lstlisting}
1459
1460// 1, 2, 3, 4, 5
1461
1462// 10, 11, 12, 13, 14, 15
1463
1464
1465\end{lstlisting}
1466\end{tabular}
1467\end{quote2}
1468
1469
1470\section{Unnamed Structure Fields}
1471
1472C requires each field of a structure to have a name, except for a bit field associated with a basic type, e.g.:
1473\begin{lstlisting}
1474struct {
1475        int f1;                 // named field
1476        int f2 : 4;             // named field with bit field size
1477        int : 3;                // unnamed field for basic type with bit field size
1478        int ;                   // disallowed, unnamed field
1479        int *;                  // disallowed, unnamed field
1480        int (*)(int);   // disallowed, unnamed field
1481};
1482\end{lstlisting}
1483This requirement is relaxed by making the field name optional for all field declarations; therefore, all the field declarations in the example are allowed.
1484As for unnamed bit fields, an unnamed field is used for padding a structure to a particular size.
1485A list of unnamed fields is also supported, e.g.:
1486\begin{lstlisting}
1487struct {
1488        int , , ;               // 3 unnamed fields
1489}
1490\end{lstlisting}
1491
1492
1493\section{Exception Handling}
1494
1495Exception handling provides two mechanim: change of control flow from a raise to a handler, and commumication from the riase to the handler.
1496\begin{lstlisting}
1497exception void h( int i );
1498exception int h( int i, double d );
1499
1500void f(...) {
1501        ... throw h( 3 );
1502        ... i = resume h( 3, 5.1 );
1503}
1504
1505try {
1506        f(...);
1507} catch h( int w ) {
1508        // reset
1509} resume h( int p, double x ) {
1510        return 17;  // recover
1511} finally {
1512}
1513\end{lstlisting}
1514So the type raised would be the mangled name of the exception prototype and that name would be matched at the handler clauses by comparing the strings.
1515The arguments for the call would have to be packed in a message and unpacked at handler clause and then a call made to the handler.
1516
1517
1518\section{Types}
1519
1520\subsection{Type Definitions}
1521
1522\CFA allows users to define new types using the keyword type.
1523
1524\begin{lstlisting}
1525// SensorValue is a distinct type and represented as an int
1526type SensorValue = int;
1527\end{lstlisting}
1528
1529A type definition is different from a typedef in C because a typedef just creates an alias for a type,  while Do.s type definition creates a distinct type.
1530This means that users can define distinct function overloads for the new type (see Overloading for more information).
1531For example:
1532
1533\begin{lstlisting}
1534type SensorValue = int;
1535void printValue(int v) {...}
1536void printValue(SensorValue v) {...}
1537void process(int v) {...}
1538
1539SensorValue s = ...;
1540
1541printValue(s); // calls version with SensorValue argument
1542
1543printValue((int) s); // calls version with int argument
1544
1545process(s); // implicit conversion to int
1546\end{lstlisting}
1547
1548If SensorValue was defined with a typedef, then these two print functions would not have unique signatures.
1549This can be very useful to create a distinct type that has the same representation as another type.
1550
1551The compiler will assume it can safely convert from the old type to the new type, implicitly.
1552Users may override this and define a function that must be called to convert from one type to another.
1553
1554\begin{lstlisting}
1555type SensorValue = int;
1556// ()? is the overloaded conversion operator identifier
1557// This function converts an int to a SensorValue
1558SensorValue ()?(int val) {
1559        ...
1560}
1561void process(int v) {...}
1562
1563SensorValue s = ...;
1564process(s); // implicit call to conversion operator
1565\end{lstlisting}
1566
1567In many cases, it is not desired for the compiler to do this implicit conversion.
1568To avoid that, the user can use the explicit modifier on the conversion operator.
1569Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error.
1570
1571\begin{lstlisting}
1572type SensorValue = int;
1573
1574// conversion from int to SensorValue; must be explicit
1575explicit SensorValue ()?(int val) {
1576        ...
1577}
1578
1579void process(int v) {...}
1580
1581SensorValue s = ...;
1582process(s); // implicit cast to int: compile-time error
1583process((int) s); // explicit cast to int: calls conversion func
1584\end{lstlisting}
1585
1586The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to:
1587\begin{lstlisting}
1588type SensorValue = int;
1589explicit SensorValue ()?(int);
1590void process(int v) {...}
1591
1592SensorValue s = ...;
1593process(s); // compile-time error
1594process((int) s); // type is converted, no function is called
1595\end{lstlisting}
1596
1597
1598\subsection{Structures}
1599
1600Structures in \CFA are basically the same as structures in C.
1601A structure is defined with the same syntax as in C.
1602When referring to a structure in \CFA, users may omit the struct keyword.
1603\begin{lstlisting}
1604struct Point {
1605        double x;
1606        double y;
1607};
1608
1609Point p = {0.0, 0.0};
1610\end{lstlisting}
1611
1612\CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields.
1613Composition is achieved by embedding one type into another.
1614When type A is embedded in type B, an object with type B may be used as an object of type A, and the fields of type A are directly accessible.
1615Embedding types is achieved using anonymous members.
1616For example, using Point from above:
1617\begin{lstlisting}
1618void foo(Point p);
1619
1620struct ColoredPoint {
1621        Point; // anonymous member (no identifier)
1622        int Color;
1623};
1624...
1625        ColoredPoint cp = ...;
1626        cp.x = 10.3; // x from Point is accessed directly
1627        cp.color = 0x33aaff; // color is accessed normally
1628        foo(cp); // cp can be used directly as a Point
1629\end{lstlisting}
1630
1631
1632\subsection{Constructors and Destructors}
1633
1634\CFA supports C initialization of structures, but it also adds constructors for more advanced initialization.
1635Additionally, \CFA adds destructors that are called when a variable is de-allocated (variable goes out of scope or object is deleted).
1636These functions take a reference to the structure as a parameter (see
1637References for more information).
1638
1639\begin{figure}
1640\begin{lstlisting}
1641struct Widget {
1642        int id;
1643        float size;
1644        Parts *optionalParts;
1645};
1646
1647// ?{} is the constructor operator identifier
1648// The first argument is a reference to the type to initialize
1649// Subsequent arguments can be specified for initialization
1650
1651void ?{}(Widget &w) { // default constructor
1652        w.id = -1;
1653        w.size = 0.0;
1654        w.optionalParts = 0;
1655}
1656
1657// constructor with values (does not need to include all fields)
1658void ?{}(Widget &w, int id, float size) {
1659        w.id = id;
1660        w.size = size;
1661        w.optionalParts = 0;
1662}
1663
1664// ^? is the destructor operator identifier
1665void ^?(Widget &w) { // destructor
1666        w.id = 0;
1667        w.size = 0.0;
1668        if (w.optionalParts != 0) {
1669        // This is the only pointer to optionalParts, free it
1670        free(w.optionalParts);
1671        w.optionalParts = 0;
1672        }
1673}
1674
1675Widget baz; // reserve space only
1676Widget foo{}; // calls default constructor
1677Widget bar{23, 2.45}; // calls constructor with values
1678baz{24, 0.91}; // calls constructor with values
1679?{}(baz, 24, 0.91}; // explicit call to constructor
1680^bar; // explicit call to destructor
1681^?(bar); // explicit call to destructor
1682\end{lstlisting}
1683\caption{Constructors and Destructors}
1684\end{figure}
1685
1686
1687\begin{comment}
1688\section{References}
1689
1690\CFA supports reference types similar to rvalue references in \CC.
1691A reference is essentially an alias for a variable, allowing multiple names to refer to the same object.
1692A reference can be used as a safer alternative to a pointer, because it can be used to pass a variable by reference, but it must always reference an object.
1693It cannot be NULL, it must be assigned a value at initialization, and the object it references cannot change once it is set.
1694By introducing references in parameter types, users are given an easy way to pass a value by reference, without the need for NULL pointer checks.
1695In structures, a reference can replace a pointer to an object that should always have a valid value.
1696When a structure contains a reference, all of its constructors must initialize the reference and all instances of this structure must initialize it upon definition.
1697
1698The syntax for using references in \CFA is the same as \CC with the exception of reference initialization.
1699Use \lstinline@&@ to specify a reference, and access references just like regular objects, not like pointers (use dot notation to access fields).
1700When initializing a reference, \CFA uses a different syntax which differentiates reference initialization from assignment to a reference.
1701The \lstinline@&@ is used on both sides of the expression to clarify that the address of the reference is being set to the address of the variable to which it refers.
1702
1703\begin{figure}
1704\begin{lstlisting}
1705// parameter p is a reference to a Point
1706void movePointUp(Point &p) {
1707        p.y += 1.0; // Uses dot-notation to access fields
1708}
1709
1710Point p1 = ...;
1711ColoredPoint cp1 = ...;
1712movePoint(p1); // reference to p1 passed to movePoint
1713movePoint(cp1); // reference to cp1 passed to movePoint
1714
1715// a ListElement cannot be created without a valid list
1716
1717struct ListElement {
1718        int element;
1719        List &list; // a list element has a reference to the list
1720}
1721
1722// The constructor must initialize the reference
1723void ?{}(ListElement &le, int e, List &l) {
1724        le.element = e;
1725        &le.list = &l; // initialize the reference
1726}
1727
1728ListElement e1{88, numberList}; // uses constructor
1729ListElement e2; // compiler error: uninitialized reference
1730Listing 10: References
1731\end{lstlisting}
1732\end{figure}
1733\end{comment}
1734
1735
1736\section{Overloading}
1737
1738Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name.
1739In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C.
1740This may cause identical C and \CFA programs to behave differently.
1741The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used.
1742Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users.
1743Disadvantages of overloading are that it can be used to give functions with different semantics the same name, causing confusion, or that the compiler may resolve to a different function from what the programmer expected.
1744\CFA allows overloading of functions, operators, variables, and even the constants 0 and 1.
1745
1746The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads.
1747The best valid interpretations are the valid interpretations that use the fewest unsafe conversions.
1748Of these, the best are those where the functions and objects involved are the least polymorphic.
1749Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions.
1750Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions.
1751If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous.
1752For details about type inference and overload resolution, please see the \CFA Language Specification.
1753\begin{lstlisting}
1754int foo(int a, int b) {
1755        float sum = 0.0;
1756        float special = 1.0;
1757        {
1758                int sum = 0;
1759                // both the float and int versions of sum are available
1760                float special = 4.0;
1761                // this inner special hides the outer version
1762                ...
1763        }
1764        ...
1765}
1766\end{lstlisting}
1767
1768
1769\subsection{Overloaded Constant}
1770
1771The constants 0 and 1 have special meaning.
1772In \CFA, as in C, all scalar types can be incremented and
1773decremented, which is defined in terms of adding or subtracting 1.
1774The operations \lstinline@&&@, \lstinline@||@, and \lstinline@!@ can be applied to any scalar arguments and are defined in terms of comparison against 0 (ex. \lstinline@(a && b)@ becomes \lstinline@(a != 0 && b != 0)@).
1775
1776In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any
1777arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a
1778special case.
1779However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their
1780functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their
1781polymorphic parameters, and user-defined pointer-like types may need a null value.
1782Defining special
1783constants for a user-defined type is more efficient than defining a conversion to the type from \lstinline@_Bool@.
1784
1785Why just 0 and 1? Why not other integers? No other integers have special status in C.
1786A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement.
1787Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed.
1788The complexity of such a feature doesn.t seem worth the gain.
1789
1790For example, to define the constants for a complex type, the programmer would define the following:
1791
1792\begin{lstlisting}
1793struct Complex {
1794        double real;
1795        double imaginary;
1796}
1797
1798const Complex 0 = {0, 0};
1799const Complex 1 = {1, 0};
1800...
1801
1802        Complex a = 0;
1803...
1804
1805        a++;
1806...
1807        if (a) { // same as if (a == 0)
1808...
1809}
1810\end{lstlisting}
1811
1812
1813\subsection{Variable Overloading}
1814
1815The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types.
1816Allowing overloading of variable names enables programmers to use the same name across multiple types, simplifying naming conventions and is compatible with the other overloading that is allowed.
1817For example, a developer may want to do the following:
1818\begin{lstlisting}
1819int pi = 3;
1820float pi = 3.14;
1821char pi = .p.;
1822\end{lstlisting}
1823
1824
1825\subsection{Function Overloading}
1826
1827Overloaded functions in \CFA are resolved based on the number and type of arguments, type of return value, and the level of specialization required (specialized functions are preferred over generic).
1828
1829The examples below give some basic intuition about how the resolution works.
1830\begin{lstlisting}
1831// Choose the one with less conversions
1832int doSomething(int value) {...} // option 1
1833int doSomething(short value) {...} // option 2
1834
1835int a, b = 4;
1836short c = 2;
1837
1838a = doSomething(b); // chooses option 1
1839a = doSomething(c); // chooses option 2
1840
1841// Choose the specialized version over the generic
1842
1843generic(type T)
1844T bar(T rhs, T lhs) {...} // option 3
1845float bar(float rhs, float lhs){...} // option 4
1846float a, b, c;
1847double d, e, f;
1848c = bar(a, b); // chooses option 4
1849
1850// specialization is preferred over unsafe conversions
1851
1852f = bar(d, e); // chooses option 5
1853\end{lstlisting}
1854
1855
1856\subsection{Operator Overloading}
1857
1858\CFA also allows operators to be overloaded, to simplify the use of user-defined types.
1859Overloading the operators allows the users to use the same syntax for their custom types that they use for built-in types, increasing readability and improving productivity.
1860\CFA uses the following special identifiers to name overloaded operators:
1861
1862\begin{table}[hbt]
1863\hfil
1864\begin{tabular}[t]{ll}
1865%identifier & operation \\ \hline
1866\lstinline@?[?]@ & subscripting \impl{?[?]}\\
1867\lstinline@?()@ & function call \impl{?()}\\
1868\lstinline@?++@ & postfix increment \impl{?++}\\
1869\lstinline@?--@ & postfix decrement \impl{?--}\\
1870\lstinline@++?@ & prefix increment \impl{++?}\\
1871\lstinline@--?@ & prefix decrement \impl{--?}\\
1872\lstinline@*?@ & dereference \impl{*?}\\
1873\lstinline@+?@ & unary plus \impl{+?}\\
1874\lstinline@-?@ & arithmetic negation \impl{-?}\\
1875\lstinline@~?@ & bitwise negation \impl{~?}\\
1876\lstinline@!?@ & logical complement \impl{"!?}\\
1877\lstinline@?*?@ & multiplication \impl{?*?}\\
1878\lstinline@?/?@ & division \impl{?/?}\\
1879\end{tabular}\hfil
1880\begin{tabular}[t]{ll}
1881%identifier & operation \\ \hline
1882\lstinline@?%?@ & remainder \impl{?%?}\\
1883\lstinline@?+?@ & addition \impl{?+?}\\
1884\lstinline@?-?@ & subtraction \impl{?-?}\\
1885\lstinline@?<<?@ & left shift \impl{?<<?}\\
1886\lstinline@?>>?@ & right shift \impl{?>>?}\\
1887\lstinline@?<?@ & less than \impl{?<?}\\
1888\lstinline@?<=?@ & less than or equal \impl{?<=?}\\
1889\lstinline@?>=?@ & greater than or equal \impl{?>=?}\\
1890\lstinline@?>?@ & greater than \impl{?>?}\\
1891\lstinline@?==?@ & equality \impl{?==?}\\
1892\lstinline@?!=?@ & inequality \impl{?"!=?}\\
1893\lstinline@?&?@ & bitwise AND \impl{?&?}\\
1894\end{tabular}\hfil
1895\begin{tabular}[t]{ll}
1896%identifier & operation \\ \hline
1897\lstinline@?^?@ & exclusive OR \impl{?^?}\\
1898\lstinline@?|?@ & inclusive OR \impl{?"|?}\\
1899\lstinline@?=?@ & simple assignment \impl{?=?}\\
1900\lstinline@?*=?@ & multiplication assignment \impl{?*=?}\\
1901\lstinline@?/=?@ & division assignment \impl{?/=?}\\
1902\lstinline@?%=?@ & remainder assignment \impl{?%=?}\\
1903\lstinline@?+=?@ & addition assignment \impl{?+=?}\\
1904\lstinline@?-=?@ & subtraction assignment \impl{?-=?}\\
1905\lstinline@?<<=?@ & left-shift assignment \impl{?<<=?}\\
1906\lstinline@?>>=?@ & right-shift assignment \impl{?>>=?}\\
1907\lstinline@?&=?@ & bitwise AND assignment \impl{?&=?}\\
1908\lstinline@?^=?@ & exclusive OR assignment \impl{?^=?}\\
1909\lstinline@?|=?@ & inclusive OR assignment \impl{?"|=?}\\
1910\end{tabular}
1911\hfil
1912\caption{Operator Identifiers}
1913\label{opids}
1914\end{table}
1915
1916These identifiers are defined such that the question marks in the name identify the location of the operands.
1917These operands represent the parameters to the functions, and define how the operands are mapped to the function call.
1918For example, \lstinline@a + b@ becomes \lstinline@?+?(a, b)@.
1919
1920In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator.
1921These operators are called using the normal C syntax.
1922
1923\begin{lstlisting}
1924type Complex = struct { // define a Complex type
1925        double real;
1926        double imag;
1927}
1928
1929// Constructor with default values
1930
1931void ?{}(Complex &c, double real = 0.0, double imag = 0.0) {
1932        c.real = real;
1933        c.imag = imag;
1934}
1935
1936Complex ?+?(Complex lhs, Complex rhs) {
1937        Complex sum;
1938        sum.real = lhs.real + rhs.real;
1939        sum.imag = lhs.imag + rhs.imag;
1940        return sum;
1941}
1942
1943String ()?(const Complex c) {
1944        // use the string conversions for the structure members
1945        return (String)c.real + . + . + (String)c.imag + .i.;
1946}
1947...
1948
1949Complex a, b, c = {1.0}; // constructor for c w/ default imag
1950...
1951c = a + b;
1952print(.sum = . + c);
1953\end{lstlisting}
1954
1955
1956\section{Auto Type-Inferencing}
1957
1958Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type.
1959\begin{quote2}
1960\begin{tabular}{@{}l@{\hspace{30pt}}ll@{}}
1961\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CC}}        & \multicolumn{1}{c}{\lstinline@gcc@}\index{gcc} \\
1962\begin{lstlisting}
1963
1964auto j = 3.0 * 4;
1965int i;
1966auto k = i;
1967\end{lstlisting}
1968&
1969\begin{lstlisting}
1970#define expr 3.0 * i
1971typeof(expr) j = expr;
1972int i;
1973typeof(i) k = i;
1974\end{lstlisting}
1975&
1976\begin{lstlisting}
1977
1978// use type of initialization expression
1979
1980// use type of primary variable
1981\end{lstlisting}
1982\end{tabular}
1983\end{quote2}
1984The two important capabilities are:
1985\begin{itemize}
1986\item
1987preventing having to determine or write out long generic types,
1988\item
1989ensure secondary variables, related to a primary variable, always have the same type.
1990\end{itemize}
1991
1992In \CFA, \lstinline@typedef@ provides a mechanism to alias long type names with short ones, both globally and locally, but not eliminate the use of the short name.
1993\lstinline@gcc@ provides \lstinline@typeof@ to declare a secondary variable from a primary variable.
1994\CFA also relies heavily on the specification of the left-hand side of assignment for type inferencing, so in many cases it is crucial to specify the type of the left-hand side to select the correct type of the right-hand expression.
1995Only for overloaded routines with the same return type is variable type-inferencing possible.
1996Finally, \lstinline@auto@ presents the programming problem of tracking down a type when the type is actually needed.
1997For example, given
1998\begin{lstlisting}
1999auto j = `...`
2000\end{lstlisting}
2001and the need to write a routine to compute using \lstinline@j@
2002\begin{lstlisting}
2003void rtn( `...` parm );
2004rtn( j );
2005\end{lstlisting}
2006A programmer must work backwards to determine the type of \lstinline@j@'s initialization expression, reconstructing the possibly long generic type-name.
2007In this situation, having the type name or a short alias is very useful.
2008
2009There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type.
2010That is, when is the type of the variable more important than the type of its initialization expression.
2011For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors.
2012At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes.
2013
2014Given \lstinline@typedef@ and \lstinline@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.
2015Should a significant need arise, this feature can be revisited.
2016
2017
2018\section{Generics}
2019
2020\CFA supports parametric polymorphism to allow users to define generic functions and types.
2021Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types.
2022The type parameters can be restricted to satisfy a set of constraints.
2023This enables \CFA to build fully compiled generic functions and types, unlike other languages like \CC where templates are expanded or must be explicitly instantiated.
2024
2025
2026\subsection{Generic Functions}
2027
2028Generic functions in \CFA are similar to template functions in \CC, and will sometimes be expanded into specialized versions, just like in \CC.
2029The difference, however, is that generic functions in \CFA can also be separately compiled, using function pointers for callers to pass in all needed functionality for the given type.
2030This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically).
2031Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated.
2032
2033A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this:
2034
2035\begin{lstlisting}
2036generic(type T)
2037void swap(T &a, T &b) {
2038        T tmp = a;
2039        a = b;
2040        b = a;
2041}
2042
2043int a, b;
2044swap(a, b);
2045
2046Point p1, p2;
2047swap(p1, p2);
2048\end{lstlisting}
2049
2050Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T.
2051This function can be called with any type, and the compiler will handle generating the proper code for that type, using call site inference to determine the appropriate value for T.
2052
2053
2054\subsection{Bounded Quantification}
2055
2056Some generic functions only work (or make sense) for any type that satisfies a given property.
2057For example, here is a function to pick the minimum of two values of some type.
2058\begin{lstlisting}
2059generic (type T | bool ?<?(T, T) )
2060
2061T min(T a, T b) {
2062        return a < b ? a : b;
2063}
2064\end{lstlisting}
2065
2066It only makes sense to call min with values of a type that has an ordering: a way to decide whether one value is less than another.
2067The ordering function used here is the less than operator, <.
2068The syntax used to reference the operator is discussed in further detail in Operator Overloading.
2069In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)).
2070The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise.
2071
2072Bounds can also involve multiple types, and multiple requirements, as shown below:
2073\begin{lstlisting}
2074generic (type T, type U | { T foo(T, U); U bar(U); })
2075
2076T baz(T t, U u) {
2077        return foo(t, bar(u));
2078}
2079\end{lstlisting}
2080
2081
2082\subsection{Interfaces}
2083
2084Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type.
2085Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined.
2086Can you define it? What is it supposed to do? Perhaps it should compute the sum, or the bitwise and, or the maximum, or the least common multiple; or perhaps it's an operation that can't be defined for integers.
2087The function signature doesn't say.
2088
2089Interfaces gather together a set of function signatures under a common name, which solves two problems.
2090First, an interface name can be used in type bounds instead of function signatures.
2091This avoids repetition when a bound is used in many functions.
2092Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand.
2093\begin{lstlisting}
2094generic (type T)
2095interface Orderable {
2096        bool ?<?(T, T);
2097};
2098
2099generic (type T | Orderable(T))
2100T min(T a, T b) {
2101        return a < b ? a : b;
2102}
2103\end{lstlisting}
2104
2105This definition of the interface Orderable makes the generic function min easier to read and understand.
2106Orderable can also be reused for other generic functions, max for example.
2107Interfaces can also build on top of other interfaces.
2108For example:
2109\begin{lstlisting}
2110generic (type T | Orderable(T)
2111interface FooBarable {
2112        int foo(T, T);
2113        int Bar(T, T);
2114};
2115\end{lstlisting}
2116
2117The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition.
2118A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time.
2119For example, there is no need to add some special syntax to show that a type implements the Orderable interface, just define a ?<? operator and it is satisfied.
2120
2121
2122\subsection{Generic Typedefs}
2123
2124Type synonyms can be defined generically using the typedef keyword together with a generic type annotation.
2125These can be used to abbreviate complicated type expressions, especially in generic code.
2126\begin{lstlisting}
2127// typedef the generic function pointers for later use
2128
2129generic(type T)
2130typedef int (*predicate)(T);
2131generic(type Captured, type T)
2132typedef void (*callback)(Captured, T);
2133
2134generic(type T)
2135void find(int length, T *array,
2136        predicate(T) p, callback(void *, T)f) {
2137        int i;
2138        for (i = 0; i < length; i++)
2139        if (p(array[i])) f(NULL, array[i]);
2140}
2141\end{lstlisting}
2142
2143
2144\subsection{Generic Types}
2145
2146Generic types are defined using the same mechanisms as those described above for generic functions.
2147This feature allows users to create types that have one or more fields that use generic parameters as types, similar to a template classes in \CC.
2148For example, to make a generic linked list, a placeholder is created for the type of the elements, so that the specific type of the elements in the list need not be specified when defining the list.
2149In C, something like this would have to be done using void pointers and unsafe casting.
2150As in generic functions, Do.s generic types are different from \CC templates in that they can be fully compiled, while \CC templates are more like macro expansions.
2151This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds.
2152
2153The syntax for defining a generic type looks very similar to that of a generic function.
2154Generic types support bounds and interfaces, using the same syntax as generic functions.
2155\begin{lstlisting}
2156generic (type T)
2157struct LinkedListElem {
2158        T elem;
2159        LinkedListElem(T) *next;
2160};
2161
2162LinkedListElem *++?(LinkedListElem **elem) {
2163        return *elem = elem->next;
2164}
2165
2166generic (type T)
2167struct LinkedList {
2168        LinkedListElem(T) *head;
2169        unsigned int size;
2170}
2171
2172generic (type T | bool ?==?(T, T))
2173bool contains(LinkedList(T) *list, T elem) {
2174        for(LinkedListElem *iter = list->head; iter != 0; ++iter) {
2175        if (iter->elem == elem) return true;
2176        }
2177        return false;
2178}
2179\end{lstlisting}
2180
2181
2182\section{Safety}
2183
2184Safety, along with productivity, is a key goal of Do.
2185This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code.
2186
2187
2188\subsection{Exceptions}
2189
2190\CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code.
2191In C, developers can use error codes and special return values to report to a caller that an error occurred in a function.
2192The major problem with error codes is that they can be easily ignored by the caller.
2193Failure to properly check for errors can result in the caller making incorrect assumptions about the current state or about the return value that are very likely to result in errors later on in the program, making the source of the problem more difficult to find when debugging.
2194An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state.
2195
2196Exceptions in \CFA allow a different type of control flow.
2197Throwing an exception terminates execution of the current block, invokes the destructors of variables that are local to the block, and propagates the exception to the parent block.
2198The exception is immediately re-thrown from the parent block unless it is caught as described below.
2199\CFA uses keywords similar to \CC for exception handling.
2200An exception is thrown using a throw statement, which accepts one argument.
2201
2202\begin{lstlisting}
2203        ...
2204
2205        throw 13;
2206
2207        ...
2208\end{lstlisting}
2209
2210An exception can be caught using a catch statement, which specifies the type of the exception it can catch.
2211A catch is specified immediately after a guarded block to signify that it can catch an exception from that block.
2212A guarded block is specified using the try keyword, followed by a block of code inside of curly braces.
2213
2214\begin{lstlisting}
2215        ...
2216
2217        try {
2218        throw 13;
2219        }
2220        catch(int e) {
2221        printf(.caught an exception: %d\n., e);
2222        }
2223\end{lstlisting}
2224
2225
2226\subsection{Memory Management}
2227
2228
2229\subsubsection{Manual Memory Management}
2230
2231Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
2232First, malloc breaks type safety because it returns a pointer to void.
2233There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
2234This problem is solved with a type-safe malloc.
2235Do.s type-safe malloc does not take any arguments for size.
2236Instead, it infers the type based on the return value, and then allocates space for the inferred type.
2237
2238\begin{lstlisting}
2239float *f = malloc(); // allocates the size of a float
2240
2241struct S {
2242        int i, j, k;
2243};
2244
2245struct S *s = malloc(); // allocates the size of a struct S
2246\end{lstlisting}
2247
2248In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
2249For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
2250
2251\begin{lstlisting}
2252type Complex = struct {
2253        float real;
2254        float imag;
2255};
2256
2257// default constructor
2258
2259void ?{}(Complex &c) {
2260        c.real = 0.0;
2261        c.imag = 0.0;
2262}
2263
2264
2265
2266// 2 parameter constructor
2267
2268void ?{}(Complex &c, float real, float imag) {
2269        c.real = real;
2270        c.imag = imag;
2271}
2272
2273
2274int main() {
2275        Complex c1; // No constructor is called
2276        Complex c2{}; // Default constructor called
2277        Complex c3{1.0, -1.0}; // 2 parameter constructor is called
2278
2279        Complex *p1 = malloc(); // allocate
2280        Complex *p2 = new(); // allocate + default constructor
2281        Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
2282}
2283
2284\end{lstlisting}
2285
2286
2287\subsubsection{Automatic Memory Management}
2288
2289\CFA may also support automatic memory management to further improve safety.
2290If 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.
2291This feature requires further investigation.
2292\CFA will not have a garbage collector, but might use some kind of region-based memory management.
2293
2294
2295\subsection{Unsafe C Constructs}
2296
2297C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
2298Some of these practices however are often error-prone and difficult to read and maintain.
2299Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
2300If 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.
2301This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
2302
2303The 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.
2304Once the full set is decided, the rules will be listed here.
2305
2306
2307\section{Syntactic Anomalies}
2308
2309The number 0 and 1 are treated specially in \CFA, and can be redefined as variables.
2310One syntactic anomaly is when a field in an structure is names 0 or 1:
2311\begin{lstlisting}
2312struct S {
2313        int 0, 1;
2314} s;
2315\end{lstlisting}
2316The problem occurs in accesing these fields using the selection operation ``\lstinline@.@'':
2317\begin{lstlisting}
2318s.0 = 0;        // ambiguity with floating constant .0
2319s.1 = 1;        // ambiguity with floating constant .1
2320\end{lstlisting}
2321To make this work, a space is required after the field selection:
2322\begin{lstlisting}
2323`s.@\textvisiblespace@0` = 0;
2324`s.@\textvisiblespace@1` = 1;
2325\end{lstlisting}
2326While this sytact is awkward, it is unlikely many programers will name fields of a structure 0 or 1.
2327Like the \CC lexical problem with closing template-syntax, e.g, \lstinline@Foo<Bar<int`>>`@, this issue can be solved with a more powerful lexer/parser.
2328
2329There are several ambiguous cases with operator identifiers, e.g., \lstinline@int *?*?()@, where the string \lstinline@*?*?@ can be lexed as \lstinline@*@/\lstinline@?*?@ or \lstinline@*?@/\lstinline@*?@.
2330Since it is common practise to put a unary operator juxtaposed to an identifier, e.g., \lstinline@*i@, users will be annoyed if they cannot do this with respect to operator identifiers.
2331Even with this special hack, there are 5 general cases that cannot be handled.
2332The first case is for the function-call identifier \lstinline@?()@:
2333\begin{lstlisting}
2334int *@\textvisiblespace@?()();  // declaration: space required after '*'
2335*@\textvisiblespace@?()();              // expression: space required after '*'
2336\end{lstlisting}
2337Without the space, the string \lstinline@*?()@ is ambiguous without N character look ahead;
2338it requires scanning ahead to determine if there is a \lstinline@'('@, which is the start of an argument/parameter list.
2339
2340The 4 remaining cases occur in expressions:
2341\begin{lstlisting}
2342i++@\textvisiblespace@?i:0;             // space required before '?'
2343i--@\textvisiblespace@?i:0;             // space required before '?'
2344i@\textvisiblespace@?++i:0;             // space required after '?'
2345i@\textvisiblespace@?--i:0;             // space required after '?'
2346\end{lstlisting}
2347In the first two cases, the string \lstinline@i++?@ is ambiguous, where this string can be lexed as \lstinline@i@ / \lstinline@++?@ or \lstinline@i++@ / \lstinline@?@;
2348it requires scanning ahead to determine if there is a \lstinline@'('@, which is the start of an argument list.
2349In the second two cases, the string \lstinline@?++x@ is ambiguous, where this string can be lexed as \lstinline@?++@ / \lstinline@x@ or \lstinline@?@ / y\lstinline@++x@;
2350it requires scanning ahead to determine if there is a \lstinline@'('@, which is the start of an argument list.
2351
2352
2353\section{Concurrency}
2354
2355Today's processors for nearly all use cases, ranging from embedded systems to large cloud computing servers, are composed of multiple cores, often heterogeneous.
2356As machines grow in complexity, it becomes more difficult for a program to make the most use of the hardware available.
2357\CFA includes built-in concurrency features to enable high performance and improve programmer productivity on these multi-/many-core machines.
2358
2359Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads.
2360The model integrates concurrency features into the language by making the structure type the core unit of concurrency.
2361All communication occurs through method calls, where data is sent via method arguments, and received via the return value.
2362This enables a very familiar interface to all programmers, even those with no parallel programming experience.
2363It also allows the compiler to do static type checking of all communication, a very important safety feature.
2364This controlled communication with type safety has some similarities with channels in Go, and can actually implement
2365channels exactly, as well as create additional communication patterns that channels cannot.
2366Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads.
2367
2368Three new keywords are added to support these features:
2369
2370monitor creates a structure with implicit locking when accessing fields
2371
2372mutex implies use of a monitor requiring the implicit locking
2373
2374task creates a type with implicit locking, separate stack, and a thread
2375
2376
2377\subsection{Monitors}
2378
2379A monitor is a structure in \CFA which includes implicit locking of its fields.
2380Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion.
2381An example of the definition of a monitor is shown here:
2382\begin{lstlisting}
2383type Account = monitor {
2384        const unsigned long number; // account number
2385        float balance; // account balance
2386};
2387\end{lstlisting}
2388
2389Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor;
2390it is always passed by reference.
2391Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter.
2392When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body.
2393This means that a function requiring mutual exclusion could block if the lock is already held by another thread.
2394Blocking on a monitor lock does not block the kernel thread, it simply blocks the user thread, which yields its kernel thread while waiting to obtain the lock.
2395If multiple mutex parameters are specified, they will be locked in parameter order (i.e. first parameter is locked first) and unlocked in the
2396reverse order.
2397\begin{lstlisting}
2398// This function accesses a constant field, it does not require
2399// mutual exclusion
2400
2401export unsigned long getAccountNumber(Account &a) {
2402        return a.number;
2403}
2404
2405// This function accesses and modifies a shared field; it
2406// requires mutual exclusion
2407
2408export float withdrawal(mutex Account &a, float amount) {
2409        a.balance -= amount;
2410        return a.balance;
2411}
2412\end{lstlisting}
2413
2414Often, one function using a monitor will call another function using that same monitor.
2415If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function.
2416This situation is resolved by allowing recursive entry (reentrant locks), meaning that if the lock is already held by the caller, it can be locked again.
2417It will still be unlocked the same number of times.
2418An example of this situation is shown below:
2419
2420\begin{lstlisting}
2421// deleting a job from a worker requires mutual exclusion
2422
2423void deleteJob(mutex Worker &w, Job &j) {
2424        ...
2425}
2426
2427// transferring requires mutual exclusion and calls deleteJob
2428
2429void transferJob(mutex Worker &from, Worker &to) {
2430        ...
2431        deleteJob(j);
2432        ...
2433}
2434\end{lstlisting}
2435
2436
2437\subsection{Tasks}
2438
2439\CFA also provides a simple mechanism for creating and utilizing user level threads.
2440A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control.
2441Similar to a monitor, a task is defined like a structure:
2442\begin{lstlisting}
2443type Adder = task {
2444        int *row;
2445        int size;
2446        int &subtotal;
2447}
2448\end{lstlisting}
2449
2450A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
2451A destructor may also be defined, which is called at de-allocation (when a dynamic object is deleted or when a local object goes out of scope).
2452After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
2453All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
2454Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
2455(Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
2456\begin{lstlisting}
2457void ?{}(Adder &a, int r[], int s, int &st) { // constructor
2458        a.row = r;
2459        a.size = s;
2460        a.subtotal = st;
2461}
2462
2463// implicitly spawn thread and begin execution here
2464
2465void ?()(Adder &a) {
2466        int c;
2467        subtotal = 0;
2468        for (c=0; c<a.size; ++c) {
2469        subtotal += row[c];
2470        }
2471}
2472
2473int main() {
2474        const int rows = 100, cols = 1000000;
2475        int matrix[rows][cols];
2476        int subtotals[rows];
2477        int total = 0;
2478        int r;
2479
2480        { // create a new scope here for our adders
2481        Adder adders[rows];
2482        // read in the matrix
2483        ...
2484        for (r=0; r<rows; ++r) {
2485        // tasks are initialized on this thread
2486        Adders[r] = {matrix[r], cols, subtotals[r]};
2487        Adders[r](); // spawn thread and begin execution
2488        }
2489        } // adders go out of scope; block here until they all finish
2490        total += subtotals[r];
2491        printf(.total is %d\n., total);
2492}
2493\end{lstlisting}
2494
2495
2496\subsection{Cooperative Scheduling}
2497
2498Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
2499In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
2500Places 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.
2501This 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.
2502For example, the code below defines a monitor that maintains a generic list.
2503When 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.
2504Similarly, 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.
2505
2506\begin{lstlisting}
2507// type T is used as a generic type for all definitions inside
2508// the curly brackets
2509
2510generic(type T) {
2511        type Channel = monitor {
2512        List(T) list; // list is a simple generic list type
2513        };
2514
2515        T pop(mutex &Channel(T) ch) {
2516        if (ch.list.empty()) {
2517        // yield until push is called for this channel
2518        yield(push);
2519        }
2520        return ch.list.pop();
2521        }
2522
2523        void push(mutex &Channel(T)ch, T val) {
2524        if (ch.list.full()) {
2525        // yield until pop is called for this channel
2526        yield(pop);
2527        }
2528        ch.list.push(val);
2529        }
2530}
2531\end{lstlisting}
2532
2533A task can also yield indefinitely by calling yield with no arguments.
2534This will tell the scheduler to yield this task until it is resumed by some other task.
2535A task can resume another task by using its functional call operator.
2536The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
2537
2538\begin{lstlisting}
2539type Ping = task {
2540        Pong *partner;
2541};
2542
2543void ?{}(Ping &p, Pong *partner = 0) {
2544        p.partner = partner;
2545}
2546
2547void ?()(Ping &p) {
2548        for(;;) { // loop forever
2549        printf(.ping\n.);
2550        partner(); // resumes the partner task
2551        yield(); // yields this task
2552        }
2553}
2554
2555type Pong = task {
2556        Ping *partner;
2557};
2558
2559void ?{}(Pong &p, Ping *partner = 0) {
2560        p.partner = partner;
2561}
2562
2563void ?()(Pong &p) {
2564        for(;;) { // loop forever
2565        yield(); // yields this task
2566        printf(.pong/n.);
2567        partner(); // resumes the partner task
2568        }
2569}
2570
2571void main() {
2572        Ping ping; // allocate ping
2573        Pong pong{ping}; // allocate, initialize, and start pong
2574        Ping{pong}; // initialize and start ping
2575}
2576\end{lstlisting}
2577
2578The same functionality can be accomplished by providing functions to be called by the partner task.
2579\begin{lstlisting}
2580type Pingpong = task {
2581        String msg;
2582        Pingpong *partner;
2583};
2584
2585void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
2586        p.msg = msg;
2587        p.partner = partner;
2588}
2589
2590void ?()(Pingpong &p) {
2591        for(;;) {
2592        yield(go);
2593        }
2594}
2595
2596void go(Pingpong &p) {
2597        print(.%(p.msg)\n.);
2598        go(p.partner);
2599}
2600
2601void main() {
2602        Pingpong ping = {.ping.};
2603        Pingpong pong = {.pong., ping};
2604        ping.partner = pong;
2605        go(ping);
2606}
2607\end{lstlisting}
2608
2609
2610\section{Modules and Packages }
2611
2612\begin{comment}
2613High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed.
2614\CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time.
2615
2616There are two levels of encapsulation in \CFA, module and package.
2617A module is a logical grouping of functionality that can be easily pulled into another project, much like a module in Python or a package in Go.
2618A module forms a namespace to limit the visibility and prevent naming conflicts of variables.
2619Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed.
2620
2621A package is a physical grouping of one or more modules that is used for code distribution and version management.
2622Package is also the level of granularity at which dependences are managed.
2623A package is similar to the Crate in Rust.
2624
2625
2626\subsection{No Declarations, No Header Files}
2627
2628In C and \CC, it is necessary to declare or define every global variable, global function, and type before it is used in each file.
2629Header files and a preprocessor are normally used to avoid repeating code.
2630Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work.
2631Instead of following this model, the \CFA tools can extract all of the same information from the code automatically.
2632This information is then stored in the object files for each module, in a format that can quickly be read by the compiler, and stored at the top of the file, for quick access.
2633In addition to the user productivity improvements, this simple change also improves compile time, by saving the information in a simple machine readable format, instead of making the compiler parse the same information over and over from a header file.
2634This seems like a minor change, but according to (Pike, Go at Google: Language Design in the Service of Software Engineering), this simple change can cause massive reductions in compile time.
2635
2636In \CFA, multiple definitions are not necessary.
2637Within a module, all of the module's global definitions are visible throughout the module.
2638For example, the following code compiles, even though isOdd was not declared before being called:
2639\begin{lstlisting}
2640bool isEven(unsigned int x) {
2641        if (x == 0) return true;
2642        else return !isOdd(x);
2643}
2644
2645bool isOdd(unsigned int x) {
2646        if (x == 1) return true;
2647        else return !isEven(x - 2);
2648}
2649\end{lstlisting}
2650
2651Header files in C are used to expose the declarations from a library, so that they can be used externally.
2652With \CFA, this functionality is replaced with module exports, discussed below.
2653When building a \CFA module which needs to be callable from C code, users can use the tools to generate a header file suitable for including in these C files with all of the needed declarations.
2654
2655In order to interoperate with existing C code, \CFA files can still include header files, the contents of which will be enclosed in a C linkage section to indicate C calling conventions (see Interoperability for more information).
2656
2657
2658\subsection{Modules}
2659
2660A module typically contains a set of related types and methods, with some objects accessible from outside the package, and some limited to use inside the module.
2661These modules can then be easily shared and reused in multiple projects.
2662As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces.
2663
2664\CFA adds the following keywords to express the module systems: module, export, import, as.
2665
2666
2667\subsubsection{Module Declaration}
2668
2669The syntax to declare a module is module moduleName;.
2670
2671The module declaration must be at the beginning of a file, and each file can only belong to one module.
2672If there is no module declaration at the beginning of a file, the file belongs to the global module.
2673A module can span several files.
2674By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation.
2675
2676The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship.
2677For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container.
2678
2679Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface.
2680A method, a global variable or a type can be declared as a module interface.
2681Types defined in a module and referenced by an exported function or a variable must be exported, too.
2682
2683The following code is a simple module declaration example.
2684\begin{lstlisting}
2685module M;
2686
2687//visible outside module M
2688
2689export int f(int i) { return i + 1; }
2690export double aCounter;
2691
2692//not visible outside module M
2693
2694int g(int i) { return i - 1; }
2695
2696double bCounter;
2697\end{lstlisting}
2698
2699export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module.
2700
2701
2702\subsubsection{Module Import}
2703
2704The syntax to import a module is import moduleName; or import moduleName as anotherName;.
2705One package cannot be imported with both of the two types of syntax in one file.
2706A package imported in one file will only be visible in this file.
2707For example, two files, A and B belong to the same module.
2708If file A imports another module, M, the exported names in M are not visible in file B.
2709
2710All of the exported names are visible in the file that imports the module.
2711The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo).
2712If moduleName has several elements separated by '/' to describe a sub-module (ex. import container/vector;), the last element in the moduleName is used as the namespace to access the visible names in that module (ex vector.add(...);).
2713The as keyword is used to confine the imported names in a unique namespace (ex. anotherName.foo). anotherName must be a valid identifier (same rules as a variable name) which means it cannot have '/' in it.
2714Conflicts in namespaces will be reported by the compiler.
2715The second method can be used to solve conflicting name problems.
2716The following code snippets show the two situations.
2717
2718\begin{lstlisting}
2719module util/counter;
2720export int f(int i) { return i+1; }
2721
2722import util/counter;
2723
2724int main() {
2725        return counter.f(200); // f() from the package counter
2726}
2727
2728import util/counter as ct;
2729int main() {
2730        return ct.f(200); // f() from the package counter
2731}
2732\end{lstlisting}
2733
2734
2735Additionally, using the .as. syntax, a user can force the compiler to add the imported names into the current namespace using .as ..With these module rules, the following module definitions and imports can be achieved without any problem.
2736
2737\begin{lstlisting}
2738module M1;
2739export int f(int i) { return i+1;} // visible outside
2740
2741int g(int i) { return i-1;} // not visible outside
2742
2743module M2;
2744int f(int i) { return i * 2; } // not visible outside
2745export int g(int g) { return i / 2; } // visible outside
2746
2747import M1 as .;
2748
2749import M2 as .;
2750
2751
2752int main() {
2753        return f(3) + g(4); //f() from M1 and g() from M2;
2754}
2755\end{lstlisting}
2756
2757
2758\subsubsection{Sub-Module and Module Aggregation}
2759
2760Several modules can be organized in a parent module and sub-modules relationship.
2761The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship.
2762For example, std/vector and std/io are sub-modules of module std.
2763The exported names in a sub-module are NOT visible if the parent module is imported, which means the exported names in the sub-module are
2764not implicitly exported in the parent module.
2765
2766Aggregation is a mechanism to support components and simplified importing.
2767The mechanism is not based on naming but based on manual declaration.
2768For example, the following is the aggregated sequence module.
2769The export {...} is syntactic sugar for many lines of export module aModule;.
2770If an aggregated module is imported, all the included modules in the aggregation are imported.
2771
2772\begin{lstlisting}
2773module std/sequence;
2774
2775export {
2776        module std/vector;
2777        module std/list;
2778        module std/array;
2779        module std/deque;
2780        module std/forward_list;
2781        module std/queue;
2782        module std/stack;
2783};
2784\end{lstlisting}
2785
2786After importing the aggregated module, each individual name is still contained in the original name space.
2787For example, vector.add() and list.add() should be used to reference the add methods if there are add methods in both the vector module and the list module.
2788
2789
2790\subsubsection{Import from Repository}
2791
2792When a module is imported, the tools locate the module in the one of the accessible package paths (defined by command line flag or environment variable).
2793The tools also support retrieving modules of a package from external repositories.
2794See Listing 40: Package directory structure
2795
2796
2797\subsubsection{Package Import}
2798
2799Because packages are the places where the building tool looks for modules, there is no code required in the \CFA source file to import a package.
2800In order to use modules in a package, the programmer needs to guide the building tool to locate the right package by 1) Adding the package's parent path into \$DOPATH;
2801or 2) Adding the package dependence into the current project's Do.prj.
2802More details about locating a module in a package are explained in the next section.
2803
2804
2805\subsubsection{Package Versioning}
2806
2807A package must have a version number.
2808The version number is a string.
2809For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
2810By convention, a package is stored in a directory named packageName-packageVersion.
2811For example, the util package with version 1.1 is stored in a directory named util-1.1.
2812
2813The project description file can optionally specify the version of the package used in the current project.
2814If not defined, because the version number is a string, and all the different versions for the same package will be sorted in increasing order, the package with the largest version number will be used in the compilation.
2815The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
2816
2817
2818\subsection{Module and Package Organization}
2819
2820\CFA has two level of encapsulations, module and package.
2821This section explains the object model of modules, packages and other language concepts.
2822It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
2823
2824
2825\subsubsection{Object Model}
2826
2827There are several concepts in Do.
2828\begin{itemize}
2829\item
2830File: a \CFA source file
2831\item
2832Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
2833\item
2834Package: a container to organize modules for distribution; It has attributes like name, author,
2835version, dependences, etc.
2836\item
2837Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
2838\end{itemize}
2839
2840The following rules summarize the object model of all the above concepts:
2841\begin{itemize}
2842\item
2843A module contains one or more files
2844\begin{itemize}
2845\item
2846One file can only belong to one module
2847\item
2848A module has its name and interfaces exported
2849\item
2850A file without a module declaration at the beginning belongs to the global module
2851\item
2852\end{itemize}
2853
2854\item
2855A package contains one or more modules
2856\begin{itemize}
2857\item
2858A package has additional meta info described in Do.prj file
2859\item
2860A package may be dependent on other packages.
2861\end{itemize}
2862
2863\item
2864A project contains one or more modules in its source code
2865\begin{itemize}
2866\item
2867A project has additional meta info described in Do.prj file
2868\item
2869A project may be dependent on other packages
2870\item
2871A project can be transformed into a package for distribution
2872\item
2873A project can generate one or more executable binaries
2874\end{itemize}
2875\end{itemize}
2876
2877
2878\subsubsection{Module File Organization}
2879
2880The rules of this section are the conventions to organize module files in one package.
2881
2882The file location of a module in a package must match the module/submodule naming hierarchy.
2883The names separated by slash "/" must match the directory levels.
2884If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
2885The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
2886
2887Here is an example of a package, util.
2888\begin{lstlisting}
2889+ util
2890Do.prj #package description file
2891        heap.do #Case 1: module heap;
2892        list.do #Case 1: mdoule list;
2893        ring.do #Case 1: module ring;
2894        + string #Case 2
2895        impl1.do #module string;
2896        + std
2897        vector.do
2898        list.do
2899        + array #Case 3
2900        array1.do #module std/array;
2901        array2.do #module std/array;
2902        sequence.do #Case 4, module std/sequence;
2903        test.do #Case 5
2904\end{lstlisting}
2905
2906\begin{itemize}
2907\item
2908Case 1: Each individual file implements a module
2909\item
2910Case 2: Put the implementation of a module under the sub-directory, but there is only one file
2911\item
2912Case 3: Put the implementation of a module under the sub-directory; There are several files to
2913implement one module
2914\item
2915Case 4: One file to express one aggregation
2916\item
2917Case 5: The file does not belong to any module; It is used for testing purpose
2918\end{itemize}
2919
2920The example only uses source code, ".do" files, to show the module file organization.
2921Other module packaging formats, like binary, must also follow the same rules.
2922
2923
2924\subsection{Module File Format}
2925
2926\CFA supports different types of module file formats.
2927
2928\begin{itemize}
2929\item
2930Pure source code format: The files should be organized following the previous section's definition.
2931\item
2932IR format (TBD): The \CFA compiler IR format, similar to the source code format
2933\item
2934Binary format, including ".a" static library or ".so" dynamic linkage library
2935\begin{itemize}
2936\item
2937The file's name must match the right level's module name defined in the previous section
2938\item
2939E.g. "util.so" includes all modules for the package util.
2940\item
2941E.g. "string.so" under the package directory to include files belonging to "module string;"
2942\end{itemize}
2943\item.
2944Archive format
2945\begin{itemize}
2946\item
2947The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
2948\item
2949E.g. "util.dar" is the whole package for util package including the package direction file
2950\end{itemize}
2951\item
2952Hybrid format
2953\begin{itemize}
2954\item
2955A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
2956\item
2957The only limitation is that the names of the files must match the module location names defined in previous section
2958\end{itemize}
2959\end{itemize}
2960Package and Module Locating and the \CFA Language Tooling documentation for more details.
2961
2962
2963\subsection{Packages}
2964
2965A package is synonymous with a library in other languages.
2966The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management.
2967A package is a physical grouping of one or more modules in a directory (an archive file for a directory).
2968The concept of a package is the convention for grouping code, and the contract between the language and the building tool to search for imported modules.
2969
2970
2971\subsubsection{Package Definition}
2972
2973A package is defined by putting a project description file, Do.prj, with one or more modules into a directory.
2974This project description file contains the package's meta data, including package name, author, version, dependences, etc.
2975It should be in the root of the package directory.
2976
2977The modules in the package could be either source code, or compiled binary format.
2978The location of the module files should follow the module name's path.
2979
2980Here is a simple example of the directory structure of a package, core.
2981It contains a module std and several sub-modules under std.
2982\begin{lstlisting}
2983+ core
2984        Do.prj
2985        + std
2986        + io
2987        file.do # module std/io/file;
2988        network.do #module std/io/network;
2989        + container
2990        vector.do #module std/container/vector;
2991        list.do #module std/container/list;
2992\end{lstlisting}
2993
2994
2995\subsubsection{Package Import}
2996
2997Because packages are the places where the building tool looks for modules, there is no code required in the \CFA source file to import a package.
2998In order to use modules in a package, the programmer needs to guide the building tool to locate the right package by 1) Adding the package's parent path into \$DOPATH; or 2) Adding the package dependence into the current project's Do.prj.
2999More details about locating a module in a package are explained in the next section.
3000
3001
3002\subsubsection{Package Versioning}
3003
3004A package must have a version number.
3005The version number is a string.
3006For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3007By convention, a package is stored in a directory named packageName-packageVersion.
3008For example, the util package with version 1.1 is stored in a directory named util-1.1.
3009
3010The project description file can optionally specify the version of the package used in the current project.
3011If not defined, because the version number is a string, and all the different versions for the same package will be sorted in increasing order, the package with the largest version number will be used in the compilation.
3012The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3013
3014
3015\subsection{Module and Package Organization}
3016
3017\CFA has two level of encapsulations, module and package.
3018This section explains the object model of modules, packages and other language concepts.
3019It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3020
3021
3022\subsubsection{Object Model}
3023
3024There are several concepts in Do.
3025\begin{itemize}
3026\item
3027File: a \CFA source file
3028\item
3029Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3030\item
3031Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc.
3032\item
3033Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3034\end{itemize}
3035
3036The following rules summarize the object model of all the above concepts:
3037\begin{itemize}
3038\item
3039A module contains one or more files
3040\begin{itemize}
3041\item
3042One file can only belong to one module
3043\item
3044A module has its name and interfaces exported
3045\item
3046A file without a module declaration at the beginning belongs to the global module
3047\end{itemize}
3048\item
3049A package contains one or more modules
3050\begin{itemize}
3051\item
3052A package has additional meta info described in Do.prj file
3053\item
3054A package may be dependent on other packages.
3055\end{itemize}
3056\item
3057A project contains one or more modules in its source code
3058\begin{itemize}
3059\item
3060A project has additional meta info described in Do.prj file
3061\item
3062A project may be dependent on other packages
3063\item
3064A project can be transformed into a package for distribution
3065\item
3066A project can generate one or more executable binaries
3067\end{itemize}
3068\end{itemize}
3069
3070
3071\subsubsection{Module File Organization}
3072
3073The rules of this section are the conventions to organize module files in one package.
3074
3075The file location of a module in a package must match the module/submodule naming hierarchy.
3076The names separated by slash "/" must match the directory levels.
3077If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3078The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3079
3080Here is an example of a package, util.
3081\begin{lstlisting}
3082+ util
3083        Do.prj #package description file
3084        heap.do #Case 1: module heap;
3085        list.do #Case 1: mdoule list;
3086        ring.do #Case 1: module ring;
3087        + string #Case 2
3088        impl1.do #module string;
3089        + std
3090        vector.do
3091        list.do
3092        + array #Case 3
3093        array1.do #module std/array;
3094        array2.do #module std/array;
3095        sequence.do #Case 4, module std/sequence;
3096        test.do #Case 5
3097\end{lstlisting}
3098
3099
3100\begin{itemize}
3101\item
3102Case 1: Each individual file implements a module
3103\item
3104Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3105\item
3106Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module
3107\item
3108Case 4: One file to express one aggregation
3109\item
3110Case 5: The file does not belong to any module; It is used for testing purpose
3111\end{itemize}
3112
3113The example only uses source code, ".do" files, to show the module file organization.
3114Other module packaging formats, like binary, must also follow the same rules.
3115
3116
3117\subsubsection{Module File Format}
3118
3119\CFA supports different types of module file formats.
3120
3121\begin{itemize}
3122\item
3123Pure source code format: The files should be organized following the previous section's definition.
3124\item
3125IR format (TBD): The \CFA compiler IR format, similar to the source code format
3126\item
3127Binary format, including ".a" static library or ".so" dynamic linkage library
3128\begin{itemize}
3129\item
3130The file's name must match the right level's module name defined in the previous section
3131\item
3132E.g. "util.so" includes all modules for the package util.
3133\item
3134E.g. "string.so" under the package directory to include files belonging to "module string;"
3135\end{itemize}
3136\item
3137Archive format
3138\begin{itemize}
3139\item
3140The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3141\item
3142E.g. "util.dar" is the whole package for util package including the package direction file
3143\end{itemize}
3144\item
3145Hybrid format
3146\begin{itemize}
3147\item
3148A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3149\item
3150The only limitation is that the names of the files must match the module location names defined in previous section
3151\end{itemize}
3152\end{itemize}
3153
3154
3155\subsection{Package and Module Locating}
3156
3157The high-level build tools provided by \CFA will handle finding a package in your local filesystem or retrieving it from a repository if necessary, building it if necessary, and linking with it.
3158If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries.
3159
3160When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order:
3161
3162\begin{enumerate}
3163\item
3164This source file's directory tree, which is typically the project's src directory
3165\item
3166All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory
3167\item
3168The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable
3169\item
3170The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory
3171\item
3172If one dependent package is still not found, the builder tool will automatically retrieve it from the repository defined in the SDK installation's configuration, and store it in the SDK's pkg directory
3173\end{enumerate}
3174
3175The module found first in a package will shadow the modules with the same name in the later packages in the search sequence.
3176
3177
3178\subsubsection{Dependent Package}
3179
3180Dependent packages are those packages containing modules that the current project's source code will import from.
3181Dependent packages are defined implicitly or explicitly in one \CFA project.
3182All of the packages under the current project's pkg directory are implicitly dependent packages.
3183For others, the dependent packages must be defined in the project's Do.prj file.
3184
3185
3186\subsubsection{Package and Module Locating Example}
3187
3188\begin{lstlisting}
3189# A project's source code tree
3190
3191--------------------------------------
3192
3193+ testProject
3194        Do.prj
3195        + src
3196        main.do
3197        + pkg
3198        + security-1.1
3199        Do.prj
3200        security.do #module security
3201
3202--------------------------------------
3203
3204# Do.prj
3205
3206--------------------------------------
3207
3208[dependences]
3209std
3210util = "0.2"
3211
3212--------------------------------------
3213
3214# main.do
3215
3216---------------------------------------
3217
3218import security;
3219import std/vector;
3220import container;
3221
3222----------------------------------------
3223\end{lstlisting}
3224
3225
3226\begin{lstlisting}
3227# pkg directory's source code tree
3228
3229-----------------------------------------
3230
3231+ pkg
3232        + std-1.0
3233        Do.prj
3234        vector.do #module std/vector;
3235        queue.do #module std/queue;
3236        + std-1.1
3237        Do.prj
3238        vector.do #module std/vector;
3239        queue.do #module std/queue;
3240        list.do #module std/list;
3241        + util-0.1
3242        Do.prj
3243        container.do #module container;
3244        + security-1.0
3245        security.do #module security;
3246------------------------------------------
3247\end{lstlisting}
3248
3249
3250During the compiling of main.do file import security;
3251The security module appears in both the local security-1.1 package, and the global security-1.0 package.
3252According to the locating sequence, the local security module in security-1.1 will be used.
3253And because the security-1.1 package is under local's pkg directory.
3254No dependence description is required in the project Do.prj file.
3255
3256import std/vector;
3257
3258The std/vector package appears in two different versions' packages in the global path and the project dependence doesn't specify the version. std-1.1 is used in this case.
3259
3260import container;
3261
3262The Do.prj specifies the version 0.2 should be used to locate container module from util package but only version 0.1 is available in the local file system.
3263The builder tool then will try to retrieve it from the web and store it in the global pkg directory.
3264After that, the container module from the newly downloaded package will be used in the compilation.
3265\end{comment}
3266
3267
3268\section{Comparison with Other Languages}
3269
3270\CFA is one of many languages that attempts to improve upon C.
3271In developing \CFA, many other languages were consulted for ideas, constructs, and syntax.
3272Therefore, it is important to show how these languages each compare with Do.
3273In this section, \CFA is compared with what the writers of this document consider to be the closest competitors of Do: \CC, Go, Rust, and D.
3274
3275
3276\subsection{Comparing Key Features of \CFA}
3277
3278
3279\subsubsection{Constructors and Destructors}
3280
3281\lstset{basicstyle=\sf\relsize{-2}}
3282
3283\begin{flushleft}
3284\begin{tabular}{@{}l|l|l|l@{}}
3285\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3286\hline
3287\begin{lstlisting}
3288struct Line {
3289        float length;
3290}
3291// default constructor
3292void ?{}( Line * l ) {
3293        sout | "default" | endl;
3294        l.length = 0.0;
3295}
3296
3297
3298// constructor with length
3299void ?{}( Line * l, float length ) {
3300        sout | "length" | length | endl;
3301
3302        l.length = length;
3303}
3304
3305// destructor
3306void ^?(Line &l) {
3307        sout | "destroyed" | endl;
3308        l.length = 0.0;
3309}
3310
3311// usage
3312Line line1;
3313Line line2{ 3.4 };
3314\end{lstlisting}
3315&
3316\begin{lstlisting}[language=C++]
3317class Line {
3318        float length;
3319
3320        // default constructor
3321        Line() {
3322                cout << "default" << endl;
3323                length = 0.0;
3324        }
3325
3326
3327        // constructor with length
3328        Line( float l ) {
3329                cout << "length " << length
3330                         << endl;
3331                length = l;
3332        }
3333
3334        // destructor
3335        ~Line() {
3336                cout << "destroyed" << endl;
3337                length = 0.0;
3338        }
3339}
3340// usage
3341Line line1;
3342Line line2( 3.4 );
3343\end{lstlisting}
3344&
3345\begin{lstlisting}[language=Golang]
3346type Line struct {
3347        length float32
3348}
3349// default constructor
3350func makeLine() Line {
3351        fmt.PrintLn( "default" )
3352        return Line{0.0}
3353}
3354
3355
3356// constructor with length
3357func makeLine( length float32 ) Line {
3358        fmt.Printf( "length %v", length )
3359
3360        return Line{length}
3361}
3362
3363// no destructor
3364
3365
3366
3367
3368
3369// usage
3370line1 := makeLine()
3371line2 := makeLine( 3.4 )
3372\end{lstlisting}
3373&
3374\begin{lstlisting}
3375struct Line {
3376        length: f32
3377}
3378// default constructor
3379impl Default for Line {
3380        fn default () -> Line {
3381                println!( "default" );
3382                Line{ length: 0.0 }
3383        }
3384}
3385// constructor with length
3386impl Line {
3387        fn make( len: f32 ) -> Line {
3388                println!( "length: {}", len );
3389                Line{ length: len }
3390        }
3391}
3392// destructor
3393impl Drop for Line {
3394        fn drop( &mut self ) {
3395                self.length = 0.0
3396        }
3397}
3398// usage
3399let line1:Line = Default::default();
3400Line line2( 3.4 );
3401\end{lstlisting}
3402\end{tabular}
3403\end{flushleft}
3404
3405
3406\subsubsection{Operator Overloading}
3407
3408\begin{flushleft}
3409\begin{tabular}{@{}l|l|l|l@{}}
3410\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3411\hline
3412\begin{lstlisting}
3413struct Cpx {
3414        double re, im;
3415};
3416// overload addition operator
3417Cpx ?+?( Cpx l, const Cpx r ) {
3418        return (Cpx){l.re+l.im, l.im+r.im};
3419}
3420Cpx a, b, c;
3421c = a + b;
3422\end{lstlisting}
3423&
3424\begin{lstlisting}
3425struct Cpx {
3426        double re, im;
3427};
3428// overload addition operator
3429Cpx operator+( Cpx l, const Cpx r ) {
3430        return (Cpx){l.re+l.im, l.im+r.im};
3431}
3432Cpx a, b, c;
3433c = a + b;
3434\end{lstlisting}
3435&
3436\begin{lstlisting}
3437// no operator overloading
3438
3439
3440
3441
3442
3443
3444
3445\end{lstlisting}
3446&
3447\begin{lstlisting}
3448struct Cpx {
3449        re: f32,
3450        im: f32
3451}
3452// overload addition operator
3453impl Add for Cpx {
3454        type Output = Cpx
3455        fn add(self, r: Cpx) -> Cpx {
3456                let mut res = Cpx{re: 0.0, im: 0.0};
3457                res.re = self.re + r.re;
3458                res.im = self.im + r.im;
3459                return res
3460        }
3461}
3462let (a, b, mut c) = ...;
3463c = a + b
3464\end{lstlisting}
3465\end{tabular}
3466\end{flushleft}
3467
3468
3469\subsubsection{Calling C Functions}
3470
3471\begin{flushleft}
3472\begin{tabular}{@{}l|l|l@{}}
3473\multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}   \\
3474\hline
3475\begin{lstlisting}[boxpos=t]
3476extern "C" {
3477#include <sys/types.h>
3478#include <sys/stat.h>
3479#include <unistd.h>
3480}
3481size_t fileSize( const char *path ) {
3482        struct stat s;
3483        stat(path, &s);
3484        return s.st_size;
3485}
3486\end{lstlisting}
3487&
3488\begin{lstlisting}[boxpos=t]
3489/*
3490#cgo
3491#include <sys/types.h>
3492#include <sys/stat.h>
3493#include <unistd.h>
3494*/
3495import "C"
3496import "unsafe"
3497
3498func fileSize(path string) C.size_t {
3499        var buf C.struct_stat
3500        c_string := C.CString(path)
3501        C.stat(p, &buf)
3502        C.free(unsafe.Pointer(c_string))
3503        return buf._st_size
3504}
3505\end{lstlisting}
3506&
3507\begin{lstlisting}[boxpos=t]
3508use libc::{c_int, size_t};
3509// translated from sys/stat.h
3510#[repr(C)]
3511struct stat_t {
3512        ...
3513        st_size: size_t,
3514        ...
3515}
3516#[link(name = "libc")]
3517extern {
3518        fn stat(path: *const u8,
3519        buf: *mut stat_t) -> c_int;
3520}
3521fn fileSize(path: *const u8) -> size_t
3522{
3523        unsafe {
3524                let mut buf: stat_t = uninit();
3525                stat(path, &mut buf);
3526                buf.st_size
3527        }
3528}
3529\end{lstlisting}
3530\end{tabular}
3531\end{flushleft}
3532
3533
3534\subsubsection{Generic Functions}
3535
3536\begin{flushleft}
3537\begin{tabular}{@{}l|l|l|l@{}}
3538\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3539\hline
3540\begin{lstlisting}
3541generic(type T, type N |
3542        { int ?<?(N, N); })
3543T *maximize(N (*f)(const T&),
3544        int n, T *a) {
3545        T *bestX = NULL;
3546        N bestN;
3547        for (int i = 0; i < n; i++) {
3548        N curN = f(a[i]);
3549        if (bestX == NULL ||
3550        curN > bestN) {
3551        bestX = &a[i]; bestN = curN;
3552        }
3553        }
3554        return bestX;
3555}
3556
3557string *longest(int n, string *p)
3558{
3559        return maximize(length, n, p);
3560}
3561\end{lstlisting}
3562&
3563\begin{lstlisting}
3564template<typename T, typename F>
3565T *maximize(const F &f,
3566        int n, T *a) {
3567        typedef decltype(f(a[0])) N;
3568        T *bestX = NULL;
3569        N bestN;
3570        for (int i = 0; i < n; i++) {
3571        N curN = f(a[i]);
3572        if (bestX == NULL || curN > bestN)
3573        {
3574        bestX = &a[i]; bestN = curN;
3575        }
3576        }
3577        return bestX;
3578}
3579
3580string *longest(int n, string *p) {
3581        return maximize(
3582        [](const string &s) {
3583        return s.length();
3584        }, n, p);
3585}
3586\end{lstlisting}
3587&
3588\begin{lstlisting}
3589// Go does not support generics!
3590func maximize(
3591        gt func(interface{}, interface{}) bool,
3592        f func(interface{}) interface{},
3593        a []interface{}) interface{} {
3594        var bestX interface{} = nil
3595        var bestN interface{} = nil
3596        for _, x := range a {
3597        curN := f(x)
3598        if bestX == nil || gt(curN, bestN)
3599        {
3600        bestN = curN
3601        bestX = x
3602        }
3603        }
3604        return bestX
3605}
3606
3607func longest(
3608        a []interface{}) interface{} {
3609        return maximize(
3610        func(a, b interface{}) bool {
3611        return a.(int) > b.(int) },
3612        func(s interface{}) interface{} {
3613        return len(s.(string)) },
3614        a).(string)
3615}
3616\end{lstlisting}
3617&
3618\begin{lstlisting}
3619use std::cmp::Ordering;
3620
3621fn maximize<N: Ord + Copy, T, F:
3622Fn(&T) -> N>(f: F, a: &Vec<T>) ->
3623Option<&T> {
3624        let mut best_x: Option<&T> = None;
3625        let mut best_n: Option<N> = None;
3626        for x in a {
3627        let n = f(x);
3628        if (match best_n { None => true,
3629        Some(bn) =>
3630        n.cmp(&bn) == Ordering::Greater })
3631        {
3632        best_x = Some(x);
3633        best_n = Some(n);
3634        }
3635        }
3636        return best_x
3637}
3638
3639fn longest(a: &Vec<String>) ->
3640        Option<&String> {
3641        return
3642        maximize(|x: &String| x.len(), a)
3643}
3644\end{lstlisting}
3645\end{tabular}
3646\end{flushleft}
3647
3648
3649\begin{comment}
3650\subsubsection{Modules/Packages}
3651
3652\begin{lstlisting}
3653\CFA
3654\CC
3655
3656
3657module example/M;
3658
3659export int inc(int val) {
3660        return val + 1;
3661}
3662
3663
3664
3665
3666--------------------------------------
3667//Use the module in another file
3668import example/M;
3669int main() {
3670        print(M.inc(100));
3671        return 0;
3672}
3673// Using \CC17 module proposal
3674
3675module example.M;
3676
3677export {
3678        int inc(int val);
3679}
3680
3681int inc(inv val) {
3682        return val + 1;
3683}
3684--------------------------------------
3685// Use the module in another file
3686import example.M;
3687int main() {
3688        cout << inc(100) << endl;
3689        return 0;
3690}
3691
3692Go
3693Rust
3694package example/M;
3695
3696func Inc(val int32) int32 {
3697        // Capitalization indicates exported
3698        return val + 100
3699}
3700
3701
3702--------------------------------------
3703//Use the package in another file
3704package main
3705import .fmt.
3706import "example/M"
3707
3708func main() int32 {
3709        fmt.Printf(.%v., M.Inc(100))
3710}
3711pub mod example {
3712        pub mod M {
3713        pub inc(val i32) -> i32 {
3714        return val + 100;
3715        }
3716        }
3717}
3718
3719--------------------------------------
3720//Use the module in another file
3721use example::M;
3722
3723
3724
3725fn main() {
3726        println!(.{}., M::inc(100));
3727}
3728\end{lstlisting}
3729\end{comment}
3730
3731
3732\subsubsection{Parallel Tasks}
3733
3734\begin{flushleft}
3735\begin{tabular}{@{}l|l|l|l@{}}
3736\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3737\hline
3738\begin{lstlisting}
3739task Nonzero {
3740        int *data;
3741        int start;
3742        int end;
3743        int* res;
3744};
3745
3746void ?{}(Nonzero &a, int d[], int s,
3747        int e, int* subres) {
3748        // constructor
3749        a.data = d;
3750        a.start = s;
3751        a.end = e;
3752        a.res = subres;
3753}
3754
3755// implicitly spawn thread here
3756void ?()(NonzeroCounter &a) {
3757        int i;
3758        int nonzero = 0;
3759        for (i=start; c<end; ++i) {
3760        if(a.data[i]!=0){ nonzero++;}
3761        }
3762        *a.res = nonzero;
3763}
3764
3765int main() {
3766        int sz = ...
3767        int data[sz] = ...;
3768        int r1 = 0, r2=0;
3769        int res;
3770        { // create a scope for Nonzero
3771        Nonzero n1{data, 0, sz/2, &n1};
3772        Nonzero n2{data, sz/2, sz, &n2};
3773        n1();//spawn
3774        n2();//spawn
3775        }
3776        res = r1+r2;
3777        return res;
3778}
3779\end{lstlisting}
3780&
3781\begin{lstlisting}
3782#include <thread>
3783#include <mutex>
3784
3785std::mutex m;
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798void task(const vector<int>&v,
3799        int* res, size_t s,
3800        size_t e) {
3801        int non_zero = 0;
3802        for(size_t i = s; i < e; ++i){
3803        if(v[i]!=0) { non_zero++;}
3804        }
3805        std::unique_lock<mutex> lck {m};
3806        *res += non_zero;
3807}
3808
3809int main() {
3810        vector<int> data = ...; //data
3811        int res = 0;
3812        std::thread t1 {task, ref(data),
3813        &res, 0,
3814        data.size()/2};
3815        std::thread t2 {task, ref(data),
3816        &res, data.size()/2,
3817        data.size()};
3818        t1.join();
3819        t2.join();
3820        return res;
3821}
3822\end{lstlisting}
3823&
3824\begin{lstlisting}
3825package main
3826
3827import "fmt"
3828
3829func nonzero(data []int, c chan int) {
3830        nz := 0
3831        for _, v:=range data {
3832        if(v!=0) { nz := nz+1 }
3833        }
3834        c <- nz
3835}
3836
3837func main() {
3838        sz := ...
3839        data := make([]int, sz)
3840        ... // data init
3841        go nonzero(data[:len(data)/2], c)
3842        go nonzero(data[len(data)/2:], c)
3843        n1, n2 := <-c, <-c
3844        res := n1 + n2
3845        fmt.Println(res)
3846}
3847\end{lstlisting}
3848&
3849\begin{lstlisting}
3850use std::thread;
3851use std::sync:mpsc::channel;
3852
3853fn main() {
3854        let sz = ...;
3855        let mut data:Vec<i32> =
3856        Vec::with_capacity(sz as usize);
3857        ... //init data
3858        let (tx, rx) = channel();
3859        for i in 0..1 {
3860        let tx = tx.clone();
3861        let data = data.clone()
3862        thread::spawn(move|| {
3863        let mut nz := 0;
3864        let mut s = 0;
3865        let mut e = sz / 2;
3866        if i == 1 {
3867        s = sz/2;
3868        e = data.len();
3869        }
3870        for i in s..(e - 1) {
3871        if data[i] != 0 (
3872        nz = nz + 1
3873        }
3874        }
3875        tx.send(nz).unwrap();
3876        });
3877        }
3878        let res = rx.recv().unwrap() +
3879        rx.recv().unwrap();
3880        println!(.{}., res);
3881}
3882\end{lstlisting}
3883\end{tabular}
3884\end{flushleft}
3885
3886\lstset{basicstyle=\sf\relsize{-1}}
3887
3888
3889\subsection{Summary of Language Comparison}
3890
3891
3892\subsubsection{\CC}
3893
3894\CC is a general-purpose programming language.
3895It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia)
3896
3897The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do.
3898\CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data.
3899\CFA uses modules instead to perform these same tasks.
3900Classes in \CC also enable inheritance among types.
3901Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility.
3902There are many studies and articles comparing inheritance and composition (or is-a versus has-a relationships), so we will not go into more detail here (Venners, 1998) (Pike, Go at Google: Language Design in the Service of Software Engineering , 2012).
3903
3904Overloading in \CFA is very similar to overloading in \CC, with the exception of the additional use, in \CFA, of the return type to differentiate between overloaded functions.
3905References and exceptions in \CFA are heavily based on the same features from \CC.
3906The mechanism for interoperating with C code in \CFA is also borrowed from \CC.
3907
3908Both \CFA and \CC provide generics, and the syntax is quite similar.
3909The key difference between the two, is that in \CC templates are expanded at compile time for each type for which the template is instantiated, while in \CFA, function pointers are used to make the generic fully compilable.
3910This means that a generic function can be defined in a compiled library, and still be used as expected from source.
3911
3912
3913\subsubsection{Go}
3914
3915Go, also commonly referred to as golang, is a programming language developed at Google in 2007 [.].
3916It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type
3917safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia)
3918
3919Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned.
3920Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction.
3921Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse.
3922Both languages also include built-in light weight, user level threading concurrency features that attempt to simplify the effort and thought process required for writing parallel programs while maintaining high performance.
3923
3924Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks.
3925\CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection.
3926This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead.
3927
3928
3929\subsubsection{Rust}
3930
3931Rust is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research.
3932It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles.
3933
3934The primary focus of Rust is in safety, especially in concurrent programs.
3935To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety.
3936This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead.
3937
3938Aside from those key differences, Rust and \CFA also have several similarities.
3939Both languages support no overhead interoperability with C and have minimal runtimes.
3940Both languages support inheritance and polymorphism through the use of interfaces (traits).
3941
3942
3943\subsubsection{D}
3944
3945The D programming language is an object-oriented, imperative, multi-paradigm system programming
3946language created by Walter Bright of Digital Mars and released in 2001. [.]
3947Though it originated as a re-engineering of \CC, D is a distinct language, having redesigned some core \CC features while also taking inspiration from other languages, notably Java, Python, Ruby, C\#, and Eiffel.
3948
3949D and \CFA both start with C and add productivity features.
3950The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces.
3951D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces.
3952Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates.
3953D does not have any built-in concurrency constructs in the
3954language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency.
3955
3956
3957\appendix
3958
3959
3960\section{Incompatible}
3961
3962The following incompatibles exist between C and \CFA, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
3963
3964\begin{enumerate}
3965\item
3966Change type of character literal \lstinline@int@ to \lstinline@char@.
3967This change allows overloading differentiation argument type matching, e.g.:
3968\begin{lstlisting}
3969int function( int i );
3970int function( char c );
3971function( 'x' );
3972\end{lstlisting}
3973It is preferable that this call match the second version of function rather than the first. \\
3974Effect on original feature: Change to semantics of well-defined feature. ISO C programs which depend on
3975\begin{lstlisting}
3976sizeof('x') == sizeof(int)
3977\end{lstlisting}
3978will not work the same as C++ programs. \\
3979Difficulty of converting: Simple. \\
3980How widely used: Programs which depend upon sizeof('x') are probably rare.
3981
3982\item
3983Change: String literals made \lstinline@const@ \\
3984The type of a string literal is changed from \lstinline@array of char@ to \lstinline@array of const char@.
3985The type of a wide string literal is changed from \lstinline@array of wchar_t@ to \lstinline@array of const wchar_t@. \\
3986Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.
3987Effect on original feature: Change to semantics of well-defined feature. \\
3988Difficulty of converting: Simple syntactic transformation, because string literals can be converted to \lstinline@char*;@ (4.2).
3989The most common cases are handled by a new but deprecated standard conversion:
3990\begin{lstlisting}
3991char* p = "abc"; // valid in C, deprecated in C++
3992char* q = expr ? "abc" : "de"; // valid in C, invalid in C++
3993\end{lstlisting}
3994How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.
3995
3996\item
3997Change: C++ does not have \emph{tentative definitions} as in C.
3998E.g., at file scope,
3999\begin{lstlisting}
4000int i;
4001int i;
4002\end{lstlisting}
4003is valid in C, invalid in C++.
4004This makes it impossible to define mutually referential file-local static
4005objects, if initializers are restricted to the syntactic forms of C. For example,
4006\begin{lstlisting}
4007struct X { int i; struct X *next; };
4008static struct X a;
4009static struct X b = { 0, &a };
4010static struct X a = { 1, &b };
4011\end{lstlisting}
4012Rationale: This avoids having different initialization rules for builtin types and userdefined types.
4013Effect on original feature: Deletion of semantically welldefined feature. \\
4014Difficulty of converting: Semantic transformation.
4015In C++, the initializer for one of a set of mutuallyreferential filelocal static objects must invoke a function call to achieve the initialization.
4016How widely used: Seldom.
4017
4018\item
4019Change: A struct is a scope in C++, not in C \\
4020Rationale: Class scope is crucial to C++, and a struct is a class. \\
4021Effect on original feature: Change to semantics of well-defined feature. \\
4022Difficulty of converting: Semantic transformation. \\
4023How 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.
4024The latter is probably rare.
4025
4026\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \CC.
4027Nested types are not hoisted and can be referenced using the field selection operator ``\lstinline@.@'', unlike the \CC scope-resolution operator ``\lstinline@::@''.
4028Given that nested types in C are equivalent to not using them, i.e., they are essentially useless, it is unlikely there are any realistic usages that break because of this incompatibility.
4029
4030
4031\item
4032Change: In C++, the name of a nested class is local to its enclosing class.
4033In C the name of the nested class belongs to the same scope as the name of the outermost enclosing class
4034Example:
4035\begin{lstlisting}
4036struct X {
4037struct Y { /* ... */ } y;
4038};
4039struct Y yy; // valid C, invalid C++
4040\end{lstlisting}
4041Rationale: C++ classes have member functions which require that classes establish scopes. The C rule
4042would leave classes as an incomplete scope mechanism which would prevent C++ programmers from maintaining
4043locality within a class. A coherent set of scope rules for C++ based on the C rule would be very
4044complicated and C++ programmers would be unable to predict reliably the meanings of nontrivial examples
4045involving nested or local functions.
4046Effect on original feature: Change of semantics of welldefined
4047feature.
4048Difficulty of converting: Semantic transformation. To make the struct type name visible in the scope of
4049the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing
4050struct is defined. Example:
4051\begin{lstlisting}
4052struct Y; // struct Y and struct X are at the same scope
4053struct X {
4054struct Y { /* ... */ } y;
4055};
4056\end{lstlisting}
4057All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of
4058the enclosing struct could be exported to the scope of the enclosing struct. Note: this is a consequence of
4059the difference in scope rules, which is documented in 3.3.
4060How widely used: Seldom.
4061\end{enumerate}
4062
4063
4064\section{I/O Library}
4065\label{s:IOLibrary}
4066\index{input/output library}
4067
4068The goal for \CFA I/O is to make I/O as simple as possible for the general case, while fully supporting polmorphism and user defined types in a consistent way.
4069The general case is printing out a sequence of variables separated by whitespace.
4070\begin{quote2}
4071\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
4072\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{\CC}}      \\
4073\begin{lstlisting}
4074int x = 0, y = 1, z = 2;
4075`sout` `|` x `|` y `|` z `| endl`;
4076\end{lstlisting}
4077&
4078\begin{lstlisting}
4079
4080cout << x << " " << y << " " << z << endl;
4081\end{lstlisting}
4082\end{tabular}
4083\end{quote2}
4084The \CFA form is half as many characters, and is similar to Python I/O with respect to implicit separators.
4085
4086The logical-or operator is used because it is the lowest-priority overloadable operator, other than assignment.
4087Therefore, fewer output expressions require parenthesis.
4088\begin{quote2}
4089\begin{tabular}{@{}ll@{}}
4090\textbf{\CFA:}
4091&
4092\begin{lstlisting}
4093sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
4094\end{lstlisting}
4095\\
4096\textbf{\CC:}
4097&
4098\begin{lstlisting}
4099cout << x * 3 << y + 1 << (z << 2) << (x == y) << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
4100\end{lstlisting}
4101\end{tabular}
4102\end{quote2}
4103Finally, the logical-or operator has a link with the Shell pipe-operator for moving data, although data flows in the opposite direction.
4104
4105The implicit seperator\index{I/O separator} character (space/blank) is a separator not a terminator.
4106The rules for implicitly adding the separator are:
4107\begin{enumerate}
4108\item
4109A seperator does not appear at the start or end of a line.
4110\begin{lstlisting}[belowskip=0pt]
4111sout 1 | 2 | 3 | endl;
4112\end{lstlisting}
4113\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
41141 2 3
4115\end{lstlisting}
4116\item
4117A seperator does not appear before or after a character literal or variable.
4118\begin{lstlisting}
4119sout | '1' | '2' | '3' | endl;
4120123
4121\end{lstlisting}
4122\item
4123A seperator does not appear before or after a null (empty) C string
4124\begin{lstlisting}
4125sout | 1 | "" | 2 | "" | 3 | endl;
4126123
4127\end{lstlisting}
4128which is a local mechanism to disable insertion of the separator character.
4129\item
4130A seperator does not appear before a C string starting with the \Index{extended ASCII}\index{ASCII} characters: \lstinline[mathescape=off]@([{$£¥¿«@
4131%$
4132\begin{lstlisting}[mathescape=off]
4133sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x $" | 4 | "x £" | 5 | "x ¥" | 6 | "x ¿" | 7 | "x «" | 8 | endl;
4134\end{lstlisting}
4135%$
4136\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4137x (1 x [2 x {3 x $4 x £5 x ¥6 x ¿7 x «8
4138\end{lstlisting}
4139%$
4140\item
4141A seperator does not appear after a C string ending with the extended ASCII characters: \lstinline@,.:;!?)]}%¢»@
4142\begin{lstlisting}[belowskip=0pt]
4143sout | 1 | ", x" | 2 | ". x" | 3 | ": x" | 4 | "; x" | 5 | "! x" | 6 | "? x" | 7 | ") x" | 8 | "] x" | 9 | "} x"
4144         | 10 | "% x" | 11 | L"¢ x" | 12 | L"» x" | endl;
4145\end{lstlisting}
4146\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
41471, x 2. x 3: x 4; x 5! x 6? x 7) x 8] x 9} x 10% x 11¢ 12»
4148\end{lstlisting}
4149\item
4150A seperator does not appear before or after a C string begining/ending with the characters: \lstinline@\f\n\r\t\v\`'"@
4151\begin{lstlisting}[belowskip=0pt]
4152sout | "x '" | 1 | "' x \`" | 2 | "\` x \"" | 3 | "\" x" | endl;
4153\end{lstlisting}
4154\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4155x '1' x \`2\` x "3" x
4156\end{lstlisting}
4157\begin{lstlisting}[showtabs=true,aboveskip=0pt]
4158sout | "x\t" | 1 | "\tx" | endl;
4159x       1       x
4160\end{lstlisting}
4161\end{enumerate}
4162The following \CC-style \Index{manipulator}s allow further control over implicit seperation.
4163\begin{lstlisting}[mathescape=off,belowskip=0pt]
4164sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
4165\end{lstlisting}
4166\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4167 1 2 3
4168\end{lstlisting}
4169\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4170sout | 1 | sepOff | 2 | 3 | endl;                       // turn off implicit separator temporarily
4171\end{lstlisting}
4172\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
417312 3
4174\end{lstlisting}
4175\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4176sout | sepDisable | 1 | 2 | 3 | endl;           // turn off implicit separation, affects all subsequent prints
4177\end{lstlisting}
4178\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4179123
4180\end{lstlisting}
4181\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4182sout | 1 | sepOn | 2 | 3 | endl;                        // turn on implicit separator temporarily
4183\end{lstlisting}
4184\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
41851 23
4186\end{lstlisting}
4187\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4188sout | sepEnable | 1 | 2 | 3 | endl;            // turn on implicit separation, affects all subsequent prints
4189\end{lstlisting}
4190\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
41911 2 3
4192\end{lstlisting}
4193\begin{lstlisting}[mathescape=off,aboveskip=0pt,aboveskip=0pt,belowskip=0pt]
4194sepSet( sout, ", $" );                                          // change separator from " " to ", $"
4195sout | 1 | 2 | 3 | endl;
4196\end{lstlisting}
4197%$
4198\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt]
41991, $2, $3
4200\end{lstlisting}
4201%$
4202\VRef[Figure]{f:ExampleIO} shows an example of input and output I/O in \CFA.
4203
4204\begin{figure}
4205\begin{lstlisting}[mathescape=off]
4206#include <fstream>
4207
4208int main() {
4209        char c;                                                                                                         // basic types
4210        short int si;
4211        unsigned short int usi;
4212        int i;
4213        unsigned int ui;
4214        long int li;
4215        unsigned long int uli;
4216        long long int lli;
4217        unsigned long long int ulli;
4218        float f;
4219        double d;
4220        long double ld;
4221        float _Complex fc;
4222        double _Complex dc;
4223        long double _Complex ldc;
4224        char s1[10], s2[10];
4225
4226        ifstream in;                                                                                            // create / open file
4227        open( &in, "input.data", "r" );
4228
4229        &in | &c                                                                                                        // character
4230                | &si | &usi | &i | &ui | &li | &uli | &lli | &ulli             // integral
4231                | &f | &d | &ld                                                                                 // floating point
4232                | &fc | &dc | &ldc                                                                              // floating-point complex
4233                | cstr( s1 ) | cstr( s2, 10 );                                                  // C string, length unchecked and checked
4234
4235        sout | c | ' ' | endl                                                                           // character
4236                 | si | usi | i | ui | li | uli | lli | ulli | endl             // integral
4237                 | f | d | ld | endl                                                                    // floating point
4238                 | fc | dc | ldc | endl;                                                                // complex
4239        sout | endl;
4240        sout | f | "" | d | "" | ld | endl                                                      // floating point without separator
4241                 | sepDisable | fc | dc | ldc | sepEnable | endl                // complex without separator
4242                 | sepOn | s1 | sepOff | s2 | endl                                              // local separator removal
4243                 | s1 | "" | s2 | endl;                                                                 // C string withou separator
4244        sout | endl;
4245        sepSet( sout, ", $" );                                                                          // change separator, maximum of 15 characters
4246        sout | f | d | ld | endl                                                                        // floating point without separator
4247                 | fc | dc | ldc | endl                                                                 // complex without separator
4248                 | s1 | s2 | endl;
4249}
4250
4251$ cat input.data
4252A 1 2 3 4 5 6 7 8 1.1 1.2 1.3 1.1+2.3 1.1-2.3 1.1-2.3 abc xyz
4253$ a.out
4254A
42551 2 3 4 5 6 7 8
42561.1 1.2 1.3
42571.1+2.3i 1.1-2.3i 1.1-2.3i
4258
42591.11.21.3
42601.1+2.3i1.1-2.3i1.1-2.3i
4261 abcxyz
4262abcxyz
4263
42641.1, $1.2, $1.3
42651.1+2.3i, $1.1-2.3i, $1.1-2.3i
4266abc, $xyz
4267\end{lstlisting}
4268\caption{Example I/O}
4269\label{f:ExampleIO}
4270\end{figure}
4271
4272
4273\section{Standard Library}
4274\label{s:StandardLibrary}
4275
4276The goal of the \CFA standard-library is to wrap many of the existing C library-routines that are explicitly polymorphic into implicitly polymorphic versions.
4277
4278
4279\subsection{malloc}
4280
4281\begin{lstlisting}
4282forall( otype T ) T * malloc( void );
4283forall( otype T ) T * malloc( char fill );
4284forall( otype T ) T * malloc( T * ptr, size_t size );
4285forall( otype T ) T * malloc( T * ptr, size_t size, unsigned char fill );
4286forall( otype T ) T * calloc( size_t size );
4287forall( otype T ) T * realloc( T * ptr, size_t size );
4288forall( otype T ) T * realloc( T * ptr, size_t size, unsigned char fill );
4289
4290forall( otype T ) T * aligned_alloc( size_t alignment );
4291forall( otype T ) T * memalign( size_t alignment );             // deprecated
4292forall( otype T ) int posix_memalign( T ** ptr, size_t alignment );
4293
4294forall( otype T ) T * memset( T * ptr, unsigned char fill ); // use default value '\0' for fill
4295forall( otype T ) T * memset( T * ptr );                                // remove when default value available
4296\end{lstlisting}
4297
4298
4299\subsection{ato/strto}
4300
4301\begin{lstlisting}
4302int ato( const char * ptr );
4303unsigned int ato( const char * ptr );
4304long int ato( const char * ptr );
4305unsigned long int ato( const char * ptr );
4306long long int ato( const char * ptr );
4307unsigned long long int ato( const char * ptr );
4308float ato( const char * ptr );
4309double ato( const char * ptr );
4310long double ato( const char * ptr );
4311float _Complex ato( const char * ptr );
4312double _Complex ato( const char * ptr );
4313long double _Complex ato( const char * ptr );
4314
4315int strto( const char * sptr, char ** eptr, int base );
4316unsigned int strto( const char * sptr, char ** eptr, int base );
4317long int strto( const char * sptr, char ** eptr, int base );
4318unsigned long int strto( const char * sptr, char ** eptr, int base );
4319long long int strto( const char * sptr, char ** eptr, int base );
4320unsigned long long int strto( const char * sptr, char ** eptr, int base );
4321float strto( const char * sptr, char ** eptr );
4322double strto( const char * sptr, char ** eptr );
4323long double strto( const char * sptr, char ** eptr );
4324float _Complex strto( const char * sptr, char ** eptr );
4325double _Complex strto( const char * sptr, char ** eptr );
4326long double _Complex strto( const char * sptr, char ** eptr );
4327\end{lstlisting}
4328
4329
4330\subsection{bsearch/qsort}
4331
4332\begin{lstlisting}
4333forall( otype T | { int ?<?( T, T ); } )
4334T * bsearch( const T key, const T * arr, size_t dimension );
4335
4336forall( otype T | { int ?<?( T, T ); } )
4337void qsort( const T * arr, size_t dimension );
4338\end{lstlisting}
4339
4340
4341\subsection{abs}
4342
4343\begin{lstlisting}
4344char abs( char );
4345extern "C" {
4346int abs( int );                         // use default C routine for int
4347} // extern "C"
4348long int abs( long int );
4349long long int abs( long long int );
4350float abs( float );
4351double abs( double );
4352long double abs( long double );
4353float _Complex abs( float _Complex );
4354double _Complex abs( double _Complex );
4355long double _Complex abs( long double _Complex );
4356\end{lstlisting}
4357
4358
4359\subsection{floor/ceil}
4360
4361\begin{lstlisting}
4362float floor( float );
4363extern "C" {
4364double floor( double );         // use C routine for double
4365} // extern "C"
4366long double floor( long double );
4367
4368float ceil( float );
4369extern "C" {
4370double ceil( double );          // use C routine for double
4371} // extern "C"
4372long double ceil( long double );
4373\end{lstlisting}
4374
4375
4376\subsection{random}
4377
4378\begin{lstlisting}
4379void rand48seed( long int s );
4380char rand48();
4381int rand48();
4382unsigned int rand48();
4383long int rand48();
4384unsigned long int rand48();
4385float rand48();
4386double rand48();
4387float _Complex rand48();
4388double _Complex rand48();
4389long double _Complex rand48();
4390\end{lstlisting}
4391
4392
4393\subsection{min/max/swap}
4394
4395\begin{lstlisting}
4396forall( otype T | { int ?<?( T, T ); } )
4397T min( const T t1, const T t2 );
4398
4399forall( otype T | { int ?>?( T, T ); } )
4400T max( const T t1, const T t2 );
4401
4402forall( otype T )
4403void swap( T * t1, T * t2 );
4404\end{lstlisting}
4405
4406
4407\section{Rational Numbers}
4408\label{s:RationalNumbers}
4409
4410Rational numbers are numbers written as a ratio, i.e., as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers.
4411When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible.
4412
4413\begin{lstlisting}
4414// implementation
4415struct Rational {
4416        long int numerator, denominator;                                        // invariant: denominator > 0
4417}; // Rational
4418
4419// constants
4420extern struct Rational 0;
4421extern struct Rational 1;
4422
4423// constructors
4424Rational rational();
4425Rational rational( long int n );
4426Rational rational( long int n, long int d );
4427
4428// getter/setter for numerator/denominator
4429long int numerator( Rational r );
4430long int numerator( Rational r, long int n );
4431long int denominator( Rational r );
4432long int denominator( Rational r, long int d );
4433
4434// comparison
4435int ?==?( Rational l, Rational r );
4436int ?!=?( Rational l, Rational r );
4437int ?<?( Rational l, Rational r );
4438int ?<=?( Rational l, Rational r );
4439int ?>?( Rational l, Rational r );
4440int ?>=?( Rational l, Rational r );
4441
4442// arithmetic
4443Rational -?( Rational r );
4444Rational ?+?( Rational l, Rational r );
4445Rational ?-?( Rational l, Rational r );
4446Rational ?*?( Rational l, Rational r );
4447Rational ?/?( Rational l, Rational r );
4448
4449// conversion
4450double widen( Rational r );
4451Rational narrow( double f, long int md );
4452
4453// I/O
4454forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * );
4455forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational );
4456\end{lstlisting}
4457
4458
4459\bibliographystyle{plain}
4460\bibliography{cfa}
4461
4462
4463\addcontentsline{toc}{section}{\indexname} % add index name to table of contents
4464\begin{theindex}
4465Italic page numbers give the location of the main entry for the referenced term.
4466Plain page numbers denote uses of the indexed term.
4467Entries for grammar non-terminals are italicized.
4468A typewriter font is used for grammar terminals and program identifiers.
4469\indexspace
4470\input{user.ind}
4471\end{theindex}
4472
4473
4474\end{document}
4475
4476% Local Variables: %
4477% tab-width: 4 %
4478% fill-column: 100 %
4479% compile-command: "make" %
4480% End: %
Note: See TracBrowser for help on using the repository browser.