source: doc/user/user.tex @ e229c22

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

change gitignore with respect to latex-generated files, small updates to manuals, replace bibtex link with actual file

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