source: doc/user/user.tex @ d395012

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 d395012 was d395012, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

support separator at end of line

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