source: doc/user/user.tex @ 3dafd83

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 3dafd83 was 3dafd83, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

update intro sections, I/O, standard headers, keywords, syntactic anomalies, constants

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