source: doc/user/user.tex @ 845cedc

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 845cedc was 6e991d6, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

add -fgnu89-inline flag to compile, cleanup swap example I/O, stdlib fixes, start math library

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