source: doc/user/user.tex @ 3873b5a1

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 3873b5a1 was 955d27e9, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Updated doc to remove signal_once

  • Property mode set to 100644
File size: 249.5 KB
Line 
1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%%
2%%
3%% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
4%%
5%% The contents of this file are covered under the licence agreement in the
6%% file "LICENCE" distributed with Cforall.
7%%
8%% user.tex --
9%%
10%% Author           : Peter A. Buhr
11%% Created On       : Wed Apr  6 14:53:29 2016
12%% Last Modified By : Peter A. Buhr
13%% Last Modified On : Sun Jul  2 09:49:56 2017
14%% Update Count     : 2503
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}
4322�_�147�_�483�_�648;                                    �\C{// decimal constant}
43356�_�ul;                                                                �\C{// decimal unsigned long constant}
4340�_�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}
441L�_��"\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 approach combines ideas from \CC and Python.
2436The \CFA header file for the I/O library is \Indexc{fstream}.
2437
2438The common case is printing out a sequence of variables separated by whitespace.
2439\begin{quote2}
2440\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
2441\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{\CC}}      \\
2442\begin{cfa}
2443int x = 1, y = 2, z = 3;
2444sout | x �|� y �|� z | endl;
2445\end{cfa}
2446&
2447\begin{cfa}
2448
2449cout << x �<< " "� << y �<< " "� << z << endl;
2450\end{cfa}
2451\\
2452\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
24531� �2� �3
2454\end{cfa}
2455&
2456\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
24571 2 3
2458\end{cfa}
2459\end{tabular}
2460\end{quote2}
2461The \CFA form has half the characters of the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators.
2462Similar simplification occurs for \Index{tuple} I/O, which prints all tuple values separated by ``\lstinline[showspaces=true]@, @''.
2463\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2464[int, [ int, int ] ] t1 = [ 1, [ 2, 3 ] ], t2 = [ 3, [ 4, 5 ] ];
2465sout | t1 | t2 | endl;                                  �\C{// print tuples}
2466\end{cfa}
2467\begin{cfa}[mathescape=off,showspaces=true,belowskip=0pt]
24681�, �2�, �3 3�, �4�, �5
2469\end{cfa}
2470Finally, \CFA uses the logical-or operator for I/O as it is the lowest-priority overloadable operator, other than assignment.
2471Therefore, fewer output expressions require parenthesis.
2472\begin{quote2}
2473\begin{tabular}{@{}ll@{}}
2474\textbf{\CFA:}
2475&
2476\begin{cfa}
2477sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
2478\end{cfa}
2479\\
2480\textbf{\CC:}
2481&
2482\begin{cfa}
2483cout << x * 3 << y + 1 << �(�z << 2�)� << �(�x == y�)� << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
2484\end{cfa}
2485\\
2486&
2487\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
24883 3 12 0 3 1 2
2489\end{cfa}
2490\end{tabular}
2491\end{quote2}
2492There 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.
2493
2494
2495\subsection{Implicit Separator}
2496
2497The \Index{implicit separator}\index{I/O!separator} character (space/blank) is a separator not a terminator.
2498The rules for implicitly adding the separator are:
2499\begin{enumerate}
2500\item
2501A separator does not appear at the start or end of a line.
2502\begin{cfa}[belowskip=0pt]
2503sout | 1 | 2 | 3 | endl;
2504\end{cfa}
2505\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
25061 2 3
2507\end{cfa}
2508
2509\item
2510A separator does not appear before or after a character literal or variable.
2511\begin{cfa}
2512sout | '1' | '2' | '3' | endl;
2513123
2514\end{cfa}
2515
2516\item
2517A separator does not appear before or after a null (empty) C string.
2518\begin{cfa}
2519sout | 1 | "" | 2 | "" | 3 | endl;
2520123
2521\end{cfa}
2522which is a local mechanism to disable insertion of the separator character.
2523
2524\item
2525A separator does not appear before a C string starting with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[mathescape=off,basicstyle=\tt]@([{=$�����@
2526%$
2527\begin{cfa}[mathescape=off]
2528sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x �" | 6 | "x �"
2529                | 7 | "x �" | 8 | "x �" | 9 | "x �" | 10 | endl;
2530\end{cfa}
2531%$
2532\begin{cfa}[mathescape=off,basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt]
2533x �(�1 x �[�2 x �{�3 x �=�4 x �$5 x ���6 x ���7 x ���8 x ���9 x ���10
2534\end{cfa}
2535%$
2536where \lstinline[basicstyle=\tt]@��@ are inverted opening exclamation and question marks, and \lstinline[basicstyle=\tt]@�@ is an opening citation mark.
2537
2538\item
2539{\lstset{language=CFA,deletedelim=**[is][]{�}{�}}
2540A seperator does not appear after a C string ending with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[basicstyle=\tt]@,.;!?)]}%��@
2541\begin{cfa}[belowskip=0pt]
2542sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x"
2543                | 7 | "� x" | 8 | "� x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl;
2544\end{cfa}
2545\begin{cfa}[basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt]
25461�,� x 2�.� x 3�;� x 4!� x 5�?� x 6%� x 7�\color{red}\textcent� x 8��� x 9�)� x 10�]� x 11�}� x
2547\end{cfa}}%
2548where \lstinline[basicstyle=\tt]@�@ is a closing citation mark.
2549
2550\item
2551A 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@
2552\begin{cfa}[belowskip=0pt]
2553sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl;
2554\end{cfa}
2555\begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt]
2556x�`�1�`�x�\color{red}\texttt{'}�2\color{red}\texttt{'}�x�\color{red}\texttt{"}�3\color{red}\texttt{"}�x�:�4�:�x� �5� �x�      �6�     �x
2557\end{cfa}
2558
2559\item
2560If a space is desired before or after one of the special string start/end characters, simply insert a space.
2561\begin{cfa}[belowskip=0pt]
2562sout | "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;
2563\end{cfa}
2564\begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt]
2565x (� �1� �) x 2� �, x 3� �:x:� �4
2566\end{cfa}
2567\end{enumerate}
2568
2569
2570\subsection{Manipulator}
2571
2572The following routines and \CC-style \Index{manipulator}s control implicit seperation.
2573\begin{enumerate}
2574\item
2575Routines \Indexc{sepSet}\index{manipulator!sepSet@�sepSet�} and \Indexc{sepGet}\index{manipulator!sepGet@�sepGet�} set and get the separator string.
2576The separator string can be at most 16 characters including the �'\0'� string terminator (15 printable characters).
2577\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2578sepSet( sout, ", $" );                                          �\C{// set separator from " " to ", \$"}
2579sout | 1 | 2 | 3 | " \"" | �sepGet( sout )� | "\"" | endl;
2580\end{cfa}
2581%$
2582\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt]
25831�, $2�, $�3 �", $"�
2584\end{cfa}
2585%$
2586\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2587sepSet( sout, " " );                                            �\C{// reset separator to " "}�
2588sout | 1 | 2 | 3 | " \"" | �sepGet( sout )� | "\"" | endl;
2589\end{cfa}
2590\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt]
25911� �2� �3 �" "�
2592\end{cfa}
2593
2594\item
2595Routine \Indexc{sepSetTuple}\index{manipulator!sepSetTuple@�sepSetTuple�} and \Indexc{sepGetTuple}\index{manipulator!sepGetTuple@�sepGetTuple�} get and set the tuple separator-string.
2596The tuple separator-string can be at most 16 characters including the �'\0'� string terminator (15 printable characters).
2597\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2598sepSetTuple( sout, " " );                                       �\C{// set tuple separator from ", " to " "}�
2599sout | t1 | t2 | " \"" | �sepGetTuple( sout )� | "\"" | endl;
2600\end{cfa}
2601\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt]
26021 2 3 4 �" "�
2603\end{cfa}
2604\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2605sepSetTuple( sout, ", " );                                      �\C{// reset tuple separator to ", "}�
2606sout | t1 | t2 | " \"" | �sepGetTuple( sout )� | "\"" | endl;
2607\end{cfa}
2608\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt]
26091, 2, 3, 4 �", "�
2610\end{cfa}
2611
2612\item
2613Manipulators \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.
2614\begin{cfa}[mathescape=off,belowskip=0pt]
2615sout | sepOn | 1 | 2 | 3 | sepOn | endl;        �\C{// separator at start/end of line}�
2616\end{cfa}
2617\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
2618� �1 2 3� �
2619\end{cfa}
2620\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2621sout | 1 | sepOff | 2 | 3 | endl;                       �\C{// locally turn off implicit separator}�
2622\end{cfa}
2623\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
262412 3
2625\end{cfa}
2626The tuple separator also responses to being turned on and off.
2627\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2628sout | sepOn | t1 | sepOff | t2 | endl;         �\C{// locally turn on/off implicit separation}�
2629\end{cfa}
2630\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
2631, 1, 23, 4
2632\end{cfa}
2633Notice a tuple seperator starts the line because the next item is a tuple.
2634
2635\item
2636Manipulators \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.
2637\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2638sout | sepDisable | 1 | 2 | 3 | endl;           �\C{// globally turn off implicit separation}�
2639\end{cfa}
2640\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
2641123
2642\end{cfa}
2643\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2644sout | 1 | �sepOn� | 2 | 3 | endl;                      �\C{// locally turn on implicit separator}�
2645\end{cfa}
2646\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
26471� �23
2648\end{cfa}
2649\begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt]
2650sout | sepEnable | 1 | 2 | 3 | endl;            �\C{// globally turn on implicit separation}�
2651\end{cfa}
2652\begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
26531 2 3
2654\end{cfa}
2655\end{enumerate}
2656
2657\begin{comment}
2658#include <fstream>
2659
2660int main( void ) {
2661        int x = 1, y = 2, z = 3;
2662        sout | x | y | z | endl;
2663        [int, [ int, int ] ] t1 = [ 1, [ 2, 3 ] ], t2 = [ 3, [ 4, 5 ] ];
2664        sout | t1 | t2 | endl;                                          // print tuples
2665        sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
2666        sout | 1 | 2 | 3 | endl;
2667        sout | '1' | '2' | '3' | endl;
2668        sout | 1 | "" | 2 | "" | 3 | endl;
2669        sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x �" | 6 | "x �"
2670                | 7 | "x �" | 8 | "x �" | 9 | "x �" | 10 | endl;
2671        sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x"
2672                | 7 | "� x" | 8 | "� x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl;
2673        sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl;
2674        sout | "x ( " | 1 | " ) x" | 2 | " , x" | 3 | " :x: " | 4 | endl;
2675
2676        sepSet( sout, ", $" );                                          // set separator from " " to ", $"
2677        sout | 1 | 2 | 3 | " \"" | sepGet( sout ) | "\"" | endl;
2678        sepSet( sout, " " );                                            // reset separator to " "
2679        sout | 1 | 2 | 3 | " \"" | sepGet( sout ) | "\"" | endl;
2680
2681        sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
2682        sout | 1 | sepOff | 2 | 3 | endl;                       // locally turn off implicit separator
2683
2684        sout | sepDisable | 1 | 2 | 3 | endl;           // globally turn off implicit separation
2685        sout | 1 | sepOn | 2 | 3 | endl;                        // locally turn on implicit separator
2686        sout | sepEnable | 1 | 2 | 3 | endl;            // globally turn on implicit separation
2687
2688        sepSetTuple( sout, " " );                                       // set tuple separator from ", " to " "
2689        sout | t1 | t2 | " \"" | sepGetTuple( sout ) | "\"" | endl;
2690        sepSetTuple( sout, ", " );                                      // reset tuple separator to ", "
2691        sout | t1 | t2 | " \"" | sepGetTuple( sout ) | "\"" | endl;
2692
2693        sout | t1 | t2 | endl;                                          // print tuple
2694        sout | sepOn | t1 | sepOff | t2 | endl;         // locally turn on/off implicit separation
2695}
2696
2697// Local Variables: //
2698// tab-width: 4 //
2699// fill-column: 100 //
2700// End: //
2701\end{comment}
2702%$
2703
2704
2705\section{Types}
2706
2707\subsection{Type Definitions}
2708
2709\CFA allows users to define new types using the keyword type.
2710
2711\begin{cfa}
2712// SensorValue is a distinct type and represented as an int
2713type SensorValue = int;
2714\end{cfa}
2715
2716A 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.
2717This means that users can define distinct function overloads for the new type (see Overloading for more information).
2718For example:
2719
2720\begin{cfa}
2721type SensorValue = int;
2722void printValue(int v) {...}
2723void printValue(SensorValue v) {...}
2724void process(int v) {...}
2725
2726SensorValue s = ...;
2727
2728printValue(s); // calls version with SensorValue argument
2729
2730printValue((int) s); // calls version with int argument
2731
2732process(s); // implicit conversion to int
2733\end{cfa}
2734
2735If SensorValue was defined with a typedef, then these two print functions would not have unique signatures.
2736This can be very useful to create a distinct type that has the same representation as another type.
2737
2738The compiler will assume it can safely convert from the old type to the new type, implicitly.
2739Users may override this and define a function that must be called to convert from one type to another.
2740
2741\begin{cfa}
2742type SensorValue = int;
2743// ()? is the overloaded conversion operator identifier
2744// This function converts an int to a SensorValue
2745SensorValue ()?(int val) {
2746        ...
2747}
2748void process(int v) {...}
2749
2750SensorValue s = ...;
2751process(s); // implicit call to conversion operator
2752\end{cfa}
2753
2754In many cases, it is not desired for the compiler to do this implicit conversion.
2755To avoid that, the user can use the explicit modifier on the conversion operator.
2756Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error.
2757
2758\begin{cfa}
2759type SensorValue = int;
2760
2761// conversion from int to SensorValue; must be explicit
2762explicit SensorValue ()?(int val) {
2763        ...
2764}
2765
2766void process(int v) {...}
2767
2768SensorValue s = ...;
2769process(s); // implicit cast to int: compile-time error
2770process((int) s); // explicit cast to int: calls conversion func
2771\end{cfa}
2772
2773The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to:
2774\begin{cfa}
2775type SensorValue = int;
2776explicit SensorValue ()?(int);
2777void process(int v) {...}
2778
2779SensorValue s = ...;
2780process(s); // compile-time error
2781process((int) s); // type is converted, no function is called
2782\end{cfa}
2783
2784
2785\subsection{Structures}
2786
2787Structures in \CFA are basically the same as structures in C.
2788A structure is defined with the same syntax as in C.
2789When referring to a structure in \CFA, users may omit the struct keyword.
2790\begin{cfa}
2791struct Point {
2792        double x;
2793        double y;
2794};
2795
2796Point p = {0.0, 0.0};
2797\end{cfa}
2798
2799\CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields.
2800Composition is achieved by embedding one type into another.
2801When 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.
2802Embedding types is achieved using anonymous members.
2803For example, using Point from above:
2804\begin{cfa}
2805void foo(Point p);
2806
2807struct ColoredPoint {
2808        Point; // anonymous member (no identifier)
2809        int Color;
2810};
2811...
2812        ColoredPoint cp = ...;
2813        cp.x = 10.3; // x from Point is accessed directly
2814        cp.color = 0x33aaff; // color is accessed normally
2815        foo(cp); // cp can be used directly as a Point
2816\end{cfa}
2817
2818
2819\section{Constructors and Destructors}
2820
2821\CFA supports C initialization of structures, but it also adds constructors for more advanced initialization.
2822Additionally, \CFA adds destructors that are called when a variable is deallocated (variable goes out of scope or object is deleted).
2823These functions take a reference to the structure as a parameter (see References for more information).
2824
2825\begin{figure}
2826\begin{cfa}
2827struct Widget {
2828        int id;
2829        float size;
2830        Parts *optionalParts;
2831};
2832
2833// ?{} is the constructor operator identifier
2834// The first argument is a reference to the type to initialize
2835// Subsequent arguments can be specified for initialization
2836
2837void ?{}(Widget &w) { // default constructor
2838        w.id = -1;
2839        w.size = 0.0;
2840        w.optionalParts = 0;
2841}
2842
2843// constructor with values (does not need to include all fields)
2844void ?{}(Widget &w, int id, float size) {
2845        w.id = id;
2846        w.size = size;
2847        w.optionalParts = 0;
2848}
2849
2850// ^? is the destructor operator identifier
2851void ^?(Widget &w) { // destructor
2852        w.id = 0;
2853        w.size = 0.0;
2854        if (w.optionalParts != 0) {
2855        // This is the only pointer to optionalParts, free it
2856        free(w.optionalParts);
2857        w.optionalParts = 0;
2858        }
2859}
2860
2861Widget baz; // reserve space only
2862Widget foo{}; // calls default constructor
2863Widget bar{23, 2.45}; // calls constructor with values
2864baz{24, 0.91}; // calls constructor with values
2865?{}(baz, 24, 0.91}; // explicit call to constructor
2866^bar; // explicit call to destructor
2867^?(bar); // explicit call to destructor
2868\end{cfa}
2869\caption{Constructors and Destructors}
2870\end{figure}
2871
2872
2873\section{Overloading}
2874
2875Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name.
2876In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C.
2877This may cause identical C and \CFA programs to behave differently.
2878The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used.
2879Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users.
2880Disadvantages 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.
2881\CFA allows overloading of functions, operators, variables, and even the constants 0 and 1.
2882
2883The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads.
2884The best valid interpretations are the valid interpretations that use the fewest unsafe conversions.
2885Of these, the best are those where the functions and objects involved are the least polymorphic.
2886Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions.
2887Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions.
2888If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous.
2889For details about type inference and overload resolution, please see the \CFA Language Specification.
2890\begin{cfa}
2891int foo(int a, int b) {
2892        float sum = 0.0;
2893        float special = 1.0;
2894        {
2895                int sum = 0;
2896                // both the float and int versions of sum are available
2897                float special = 4.0;
2898                // this inner special hides the outer version
2899                ...
2900        }
2901        ...
2902}
2903\end{cfa}
2904
2905
2906\subsection{Overloaded Constant}
2907
2908The constants 0 and 1 have special meaning.
2909In \CFA, as in C, all scalar types can be incremented and
2910decremented, which is defined in terms of adding or subtracting 1.
2911The 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)�).
2912
2913In 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.
2914However, 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.
2915Defining special constants for a user-defined type is more efficient than defining a conversion to the type from �_Bool�.
2916
2917Why just 0 and 1? Why not other integers? No other integers have special status in C.
2918A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement.
2919Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed.
2920The complexity of such a feature does not seem worth the gain.
2921
2922For example, to define the constants for a complex type, the programmer would define the following:
2923
2924\begin{cfa}
2925struct Complex {
2926        double real;
2927        double imaginary;
2928}
2929
2930const Complex 0 = {0, 0};
2931const Complex 1 = {1, 0};
2932...
2933
2934        Complex a = 0;
2935...
2936
2937        a++;
2938...
2939        if (a) { // same as if (a == 0)
2940...
2941}
2942\end{cfa}
2943
2944
2945\subsection{Variable Overloading}
2946
2947The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types.
2948Allowing 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.
2949For example, a developer may want to do the following:
2950\begin{cfa}
2951int pi = 3;
2952float pi = 3.14;
2953char pi = .p.;
2954\end{cfa}
2955
2956
2957\subsection{Function Overloading}
2958
2959Overloaded 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).
2960
2961The examples below give some basic intuition about how the resolution works.
2962\begin{cfa}
2963// Choose the one with less conversions
2964int doSomething(int value) {...} // option 1
2965int doSomething(short value) {...} // option 2
2966
2967int a, b = 4;
2968short c = 2;
2969
2970a = doSomething(b); // chooses option 1
2971a = doSomething(c); // chooses option 2
2972
2973// Choose the specialized version over the generic
2974
2975generic(type T)
2976T bar(T rhs, T lhs) {...} // option 3
2977float bar(float rhs, float lhs){...} // option 4
2978float a, b, c;
2979double d, e, f;
2980c = bar(a, b); // chooses option 4
2981
2982// specialization is preferred over unsafe conversions
2983
2984f = bar(d, e); // chooses option 5
2985\end{cfa}
2986
2987
2988\subsection{Operator Overloading}
2989
2990\CFA also allows operators to be overloaded, to simplify the use of user-defined types.
2991Overloading 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.
2992\CFA uses the following special identifiers to name overloaded operators:
2993
2994\begin{table}[hbt]
2995\hfil
2996\begin{tabular}[t]{ll}
2997%identifier & operation \\ \hline
2998�?[?]� & subscripting \impl{?[?]}\\
2999�?()� & function call \impl{?()}\\
3000�?++� & postfix increment \impl{?++}\\
3001�?--� & postfix decrement \impl{?--}\\
3002�++?� & prefix increment \impl{++?}\\
3003�--?� & prefix decrement \impl{--?}\\
3004�*?� & dereference \impl{*?}\\
3005�+?� & unary plus \impl{+?}\\
3006�-?� & arithmetic negation \impl{-?}\\
3007�~?� & bitwise negation \impl{~?}\\
3008�!?� & logical complement \impl{"!?}\\
3009�?*?� & multiplication \impl{?*?}\\
3010�?/?� & division \impl{?/?}\\
3011\end{tabular}\hfil
3012\begin{tabular}[t]{ll}
3013%identifier & operation \\ \hline
3014�?%?� & remainder \impl{?%?}\\
3015�?+?� & addition \impl{?+?}\\
3016�?-?� & subtraction \impl{?-?}\\
3017�?<<?� & left shift \impl{?<<?}\\
3018�?>>?� & right shift \impl{?>>?}\\
3019�?<?� & less than \impl{?<?}\\
3020�?<=?� & less than or equal \impl{?<=?}\\
3021�?>=?� & greater than or equal \impl{?>=?}\\
3022�?>?� & greater than \impl{?>?}\\
3023�?==?� & equality \impl{?==?}\\
3024�?!=?� & inequality \impl{?"!=?}\\
3025�?&?� & bitwise AND \impl{?&?}\\
3026\end{tabular}\hfil
3027\begin{tabular}[t]{ll}
3028%identifier & operation \\ \hline
3029�?^?� & exclusive OR \impl{?^?}\\
3030�?|?� & inclusive OR \impl{?"|?}\\
3031�?=?� & simple assignment \impl{?=?}\\
3032�?*=?� & multiplication assignment \impl{?*=?}\\
3033�?/=?� & division assignment \impl{?/=?}\\
3034�?%=?� & remainder assignment \impl{?%=?}\\
3035�?+=?� & addition assignment \impl{?+=?}\\
3036�?-=?� & subtraction assignment \impl{?-=?}\\
3037�?<<=?� & left-shift assignment \impl{?<<=?}\\
3038�?>>=?� & right-shift assignment \impl{?>>=?}\\
3039�?&=?� & bitwise AND assignment \impl{?&=?}\\
3040�?^=?� & exclusive OR assignment \impl{?^=?}\\
3041�?|=?� & inclusive OR assignment \impl{?"|=?}\\
3042\end{tabular}
3043\hfil
3044\caption{Operator Identifiers}
3045\label{opids}
3046\end{table}
3047
3048These identifiers are defined such that the question marks in the name identify the location of the operands.
3049These operands represent the parameters to the functions, and define how the operands are mapped to the function call.
3050For example, �a + b� becomes �?+?(a, b)�.
3051
3052In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator.
3053These operators are called using the normal C syntax.
3054
3055\begin{cfa}
3056type Complex = struct { // define a Complex type
3057        double real;
3058        double imag;
3059}
3060
3061// Constructor with default values
3062
3063void ?{}(Complex &c, double real = 0.0, double imag = 0.0) {
3064        c.real = real;
3065        c.imag = imag;
3066}
3067
3068Complex ?+?(Complex lhs, Complex rhs) {
3069        Complex sum;
3070        sum.real = lhs.real + rhs.real;
3071        sum.imag = lhs.imag + rhs.imag;
3072        return sum;
3073}
3074
3075String ()?(const Complex c) {
3076        // use the string conversions for the structure members
3077        return (String)c.real + . + . + (String)c.imag + .i.;
3078}
3079...
3080
3081Complex a, b, c = {1.0}; // constructor for c w/ default imag
3082...
3083c = a + b;
3084print(.sum = . + c);
3085\end{cfa}
3086
3087
3088\section{Auto Type-Inferencing}
3089
3090Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type.
3091\begin{quote2}
3092\begin{tabular}{@{}l@{\hspace{3em}}ll@{}}
3093\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\Indexc{gcc}}} \\
3094\begin{cfa}
3095
3096auto j = 3.0 * 4;
3097int i;
3098auto k = i;
3099\end{cfa}
3100&
3101\begin{cfa}
3102#define expr 3.0 * i
3103typeof(expr) j = expr;
3104int i;
3105typeof(i) k = i;
3106\end{cfa}
3107&
3108\begin{cfa}
3109
3110// use type of initialization expression
3111
3112// use type of primary variable
3113\end{cfa}
3114\end{tabular}
3115\end{quote2}
3116The two important capabilities are:
3117\begin{itemize}
3118\item
3119preventing having to determine or write out long generic types,
3120\item
3121ensure secondary variables, related to a primary variable, always have the same type.
3122\end{itemize}
3123
3124In \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.
3125\Indexc{gcc} provides �typeof� to declare a secondary variable from a primary variable.
3126\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.
3127Only for overloaded routines with the same return type is variable type-inferencing possible.
3128Finally, �auto� presents the programming problem of tracking down a type when the type is actually needed.
3129For example, given
3130\begin{cfa}
3131auto j = �...�
3132\end{cfa}
3133and the need to write a routine to compute using �j�
3134\begin{cfa}
3135void rtn( �...� parm );
3136rtn( j );
3137\end{cfa}
3138A programmer must work backwards to determine the type of �j�'s initialization expression, reconstructing the possibly long generic type-name.
3139In this situation, having the type name or a short alias is very useful.
3140
3141There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type.
3142That is, when is the type of the variable more important than the type of its initialization expression.
3143For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors.
3144At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes.
3145
3146Given �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.
3147Should a significant need arise, this feature can be revisited.
3148
3149
3150\begin{comment}
3151\section{Generics}
3152
3153\CFA supports parametric polymorphism to allow users to define generic functions and types.
3154Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types.
3155The type parameters can be restricted to satisfy a set of constraints.
3156This 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.
3157
3158
3159\subsection{Generic Functions}
3160
3161Generic functions in \CFA are similar to template functions in \Index*[C++]{\CC{}}, and will sometimes be expanded into specialized versions, just like in \CC.
3162The 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.
3163This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically).
3164Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated.
3165
3166A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this:
3167
3168\begin{cfa}
3169generic(type T)
3170void swap(T &a, T &b) {
3171        T tmp = a;
3172        a = b;
3173        b = a;
3174}
3175
3176int a, b;
3177swap(a, b);
3178
3179Point p1, p2;
3180swap(p1, p2);
3181\end{cfa}
3182
3183Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T.
3184This 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.
3185
3186
3187\subsection{Bounded Quantification}
3188
3189Some generic functions only work (or make sense) for any type that satisfies a given property.
3190For example, here is a function to pick the minimum of two values of some type.
3191\begin{cfa}
3192generic (type T | bool ?<?(T, T) )
3193
3194T min( T a, T b ) {
3195        return a < b ? a : b;
3196}
3197\end{cfa}
3198
3199It 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.
3200The ordering function used here is the less than operator, <.
3201The syntax used to reference the operator is discussed in further detail in Operator Overloading.
3202In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)).
3203The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise.
3204
3205Bounds can also involve multiple types, and multiple requirements, as shown below:
3206\begin{cfa}
3207generic (type T, type U | { T foo(T, U); U bar(U); })
3208
3209T baz(T t, U u) {
3210        return foo(t, bar(u));
3211}
3212\end{cfa}
3213
3214
3215\subsection{Interfaces}
3216
3217Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type.
3218Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined.
3219Can 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.
3220The function signature doesn't say.
3221
3222Interfaces gather together a set of function signatures under a common name, which solves two problems.
3223First, an interface name can be used in type bounds instead of function signatures.
3224This avoids repetition when a bound is used in many functions.
3225Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand.
3226\begin{cfa}
3227generic (type T)
3228interface Orderable {
3229        bool ?<?(T, T);
3230};
3231
3232generic (type T | Orderable(T))
3233T min( T a, T b ) {
3234        return a < b ? a : b;
3235}
3236\end{cfa}
3237
3238This definition of the interface Orderable makes the generic function min easier to read and understand.
3239Orderable can also be reused for other generic functions, max for example.
3240Interfaces can also build on top of other interfaces.
3241For example:
3242\begin{cfa}
3243generic (type T | Orderable(T)
3244interface FooBarable {
3245        int foo(T, T);
3246        int Bar(T, T);
3247};
3248\end{cfa}
3249
3250The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition.
3251A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time.
3252For 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.
3253
3254
3255\subsection{Generic Typedefs}
3256
3257Type synonyms can be defined generically using the typedef keyword together with a generic type annotation.
3258These can be used to abbreviate complicated type expressions, especially in generic code.
3259\begin{cfa}
3260// typedef the generic function pointers for later use
3261
3262generic(type T)
3263typedef int (*predicate)(T);
3264generic(type Captured, type T)
3265typedef void (*callback)(Captured, T);
3266
3267generic(type T)
3268void find(int length, T *array,
3269        predicate(T) p, callback(void *, T)f) {
3270        int i;
3271        for (i = 0; i < length; i++)
3272        if (p(array[i])) f(NULL, array[i]);
3273}
3274\end{cfa}
3275
3276
3277\subsection{Generic Types}
3278
3279Generic types are defined using the same mechanisms as those described above for generic functions.
3280This 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{}}.
3281For 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.
3282In C, something like this would have to be done using void pointers and unsafe casting.
3283As 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.
3284This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds.
3285
3286The syntax for defining a generic type looks very similar to that of a generic function.
3287Generic types support bounds and interfaces, using the same syntax as generic functions.
3288\begin{cfa}
3289generic (type T)
3290struct LinkedListElem {
3291        T elem;
3292        LinkedListElem(T) *next;
3293};
3294
3295LinkedListElem *++?(LinkedListElem **elem) {
3296        return *elem = elem->next;
3297}
3298
3299generic (type T)
3300struct LinkedList {
3301        LinkedListElem(T) *head;
3302        unsigned int size;
3303}
3304
3305generic (type T | bool ?==?(T, T))
3306bool contains(LinkedList(T) *list, T elem) {
3307        for(LinkedListElem *iter = list->head; iter != 0; ++iter) {
3308        if (iter->elem == elem) return true;
3309        }
3310        return false;
3311}
3312\end{cfa}
3313
3314
3315\section{Safety}
3316
3317Safety, along with productivity, is a key goal of Do.
3318This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code.
3319
3320
3321\subsection{Exceptions}
3322
3323\CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code.
3324In C, developers can use error codes and special return values to report to a caller that an error occurred in a function.
3325The major problem with error codes is that they can be easily ignored by the caller.
3326Failure 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.
3327An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state.
3328
3329Exceptions in \CFA allow a different type of control flow.
3330Throwing 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.
3331The exception is immediately re-thrown from the parent block unless it is caught as described below.
3332\CFA uses keywords similar to \Index*[C++]{\CC{}} for exception handling.
3333An exception is thrown using a throw statement, which accepts one argument.
3334
3335\begin{cfa}
3336        ...
3337
3338        throw 13;
3339
3340        ...
3341\end{cfa}
3342
3343An exception can be caught using a catch statement, which specifies the type of the exception it can catch.
3344A catch is specified immediately after a guarded block to signify that it can catch an exception from that block.
3345A guarded block is specified using the try keyword, followed by a block of code inside of curly braces.
3346
3347\begin{cfa}
3348        ...
3349
3350        try {
3351                throw 13;
3352        }
3353        catch(int e) {
3354                printf(.caught an exception: %d\n., e);
3355        }
3356\end{cfa}
3357\end{comment}
3358
3359
3360\subsection{Memory Management}
3361
3362
3363\subsubsection{Manual Memory Management}
3364
3365Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
3366First, malloc breaks type safety because it returns a pointer to void.
3367There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
3368This problem is solved with a type-safe malloc.
3369Do.s type-safe malloc does not take any arguments for size.
3370Instead, it infers the type based on the return value, and then allocates space for the inferred type.
3371
3372\begin{cfa}
3373float *f = malloc(); // allocates the size of a float
3374
3375struct S {
3376        int i, j, k;
3377};
3378
3379struct S *s = malloc(); // allocates the size of a struct S
3380\end{cfa}
3381
3382In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
3383For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
3384
3385\begin{cfa}
3386type Complex = struct {
3387        float real;
3388        float imag;
3389};
3390
3391// default constructor
3392
3393void ?{}(Complex &c) {
3394        c.real = 0.0;
3395        c.imag = 0.0;
3396}
3397
3398
3399
3400// 2 parameter constructor
3401
3402void ?{}(Complex &c, float real, float imag) {
3403        c.real = real;
3404        c.imag = imag;
3405}
3406
3407
3408int main() {
3409        Complex c1; // No constructor is called
3410        Complex c2{}; // Default constructor called
3411        Complex c3{1.0, -1.0}; // 2 parameter constructor is called
3412
3413        Complex *p1 = malloc(); // allocate
3414        Complex *p2 = new(); // allocate + default constructor
3415        Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
3416}
3417\end{cfa}
3418
3419
3420\subsubsection{Automatic Memory Management}
3421
3422\CFA may also support automatic memory management to further improve safety.
3423If 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.
3424This feature requires further investigation.
3425\CFA will not have a garbage collector, but might use some kind of region-based memory management.
3426
3427
3428\begin{comment}
3429\subsection{Unsafe C Constructs}
3430
3431C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
3432Some of these practices however are often error-prone and difficult to read and maintain.
3433Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
3434If 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.
3435This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
3436
3437The 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.
3438Once the full set is decided, the rules will be listed here.
3439\end{comment}
3440
3441
3442\section{Concurrency}
3443
3444Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads.
3445The model integrates concurrency features into the language by making the structure type the core unit of concurrency.
3446All communication occurs through method calls, where data is sent via method arguments, and received via the return value.
3447This enables a very familiar interface to all programmers, even those with no parallel programming experience.
3448It also allows the compiler to do static type checking of all communication, a very important safety feature.
3449This 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.
3450Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads.
3451
3452\begin{figure}
3453\begin{cfa}
3454#include <fstream>
3455#include <coroutine>
3456
3457coroutine Fibonacci {
3458        int fn;                                                         �\C{// used for communication}
3459};
3460void ?{}( Fibonacci * this ) {
3461        this->fn = 0;
3462}
3463void main( Fibonacci * this ) {
3464        int fn1, fn2;                                           �\C{// retained between resumes}
3465        this->fn = 0;                                           �\C{// case 0}
3466        fn1 = this->fn;
3467        suspend();                                                      �\C{// return to last resume}
3468
3469        this->fn = 1;                                           �\C{// case 1}
3470        fn2 = fn1;
3471        fn1 = this->fn;
3472        suspend();                                                      �\C{// return to last resume}
3473
3474        for ( ;; ) {                                            �\C{// general case}
3475                this->fn = fn1 + fn2;
3476                fn2 = fn1;
3477                fn1 = this->fn;
3478                suspend();                                              �\C{// return to last resume}
3479        } // for
3480}
3481int next( Fibonacci * this ) {
3482        resume( this );                                         �\C{// transfer to last suspend}
3483        return this->fn;
3484}
3485int main() {
3486        Fibonacci f1, f2;
3487        for ( int i = 1; i <= 10; i += 1 ) {
3488                sout | next( &f1 ) | ' ' | next( &f2 ) | endl;
3489        } // for
3490}
3491\end{cfa}
3492\caption{Fibonacci Coroutine}
3493\label{f:FibonacciCoroutine}
3494\end{figure}
3495
3496
3497\subsection{Coroutine}
3498
3499\Index{Coroutines} are the precursor to tasks.
3500\VRef[Figure]{f:FibonacciCoroutine} shows a coroutine that computes the \Index*{Fibonacci} numbers.
3501
3502
3503\subsection{Monitors}
3504
3505A monitor is a structure in \CFA which includes implicit locking of its fields.
3506Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion.
3507An example of the definition of a monitor is shown here:
3508\begin{cfa}
3509type Account = monitor {
3510        const unsigned long number; // account number
3511        float balance; // account balance
3512};
3513\end{cfa}
3514
3515\begin{figure}
3516\begin{cfa}
3517#include <fstream>
3518#include <kernel>
3519#include <monitor>
3520#include <thread>
3521
3522monitor global_t {
3523        int value;
3524};
3525
3526void ?{}(global_t * this) {
3527        this->value = 0;
3528}
3529
3530static global_t global;
3531
3532void increment3( global_t * mutex this ) {
3533        this->value += 1;
3534}
3535void increment2( global_t * mutex this ) {
3536        increment3( this );
3537}
3538void increment( global_t * mutex this ) {
3539        increment2( this );
3540}
3541
3542thread MyThread {};
3543
3544void main( MyThread* this ) {
3545        for(int i = 0; i < 1_000_000; i++) {
3546                increment( &global );
3547        }
3548}
3549int main(int argc, char* argv[]) {
3550        processor p;
3551        {
3552                MyThread f[4];
3553        }
3554        sout | global.value | endl;
3555}
3556\end{cfa}
3557\caption{Atomic-Counter Monitor}
3558\caption{f:AtomicCounterMonitor}
3559\end{figure}
3560
3561\begin{comment}
3562Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor;
3563it is always passed by reference.
3564Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter.
3565When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body.
3566This means that a function requiring mutual exclusion could block if the lock is already held by another thread.
3567Blocking 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.
3568If multiple mutex parameters are specified, they will be locked in parameter order (\ie first parameter is locked first) and unlocked in the
3569reverse order.
3570\begin{cfa}
3571// This function accesses a constant field, it does not require
3572// mutual exclusion
3573
3574export unsigned long getAccountNumber(Account &a) {
3575        return a.number;
3576}
3577
3578// This function accesses and modifies a shared field; it
3579// requires mutual exclusion
3580
3581export float withdrawal(mutex Account &a, float amount) {
3582        a.balance -= amount;
3583        return a.balance;
3584}
3585\end{cfa}
3586
3587Often, one function using a monitor will call another function using that same monitor.
3588If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function.
3589This 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.
3590It will still be unlocked the same number of times.
3591An example of this situation is shown below:
3592
3593\begin{cfa}
3594// deleting a job from a worker requires mutual exclusion
3595
3596void deleteJob(mutex Worker &w, Job &j) {
3597        ...
3598}
3599
3600// transferring requires mutual exclusion and calls deleteJob
3601
3602void transferJob(mutex Worker &from, Worker &to) {
3603        ...
3604        deleteJob(j);
3605        ...
3606}
3607\end{cfa}
3608\end{comment}
3609
3610
3611\subsection{Tasks}
3612
3613\CFA also provides a simple mechanism for creating and utilizing user level threads.
3614A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control.
3615Similar to a monitor, a task is defined like a structure:
3616
3617\begin{figure}
3618\begin{cfa}
3619#include <fstream>
3620#include <kernel>
3621#include <stdlib>
3622#include <thread>
3623
3624thread First  { semaphore* lock; };
3625thread Second { semaphore* lock; };
3626
3627void ?{}( First * this, semaphore* lock ) { this->lock = lock; }
3628void ?{}( Second * this, semaphore* lock ) { this->lock = lock; }
3629
3630void main(First* this) {
3631        for(int i = 0; i < 10; i++) {
3632                sout | "First : Suspend No." | i + 1 | endl;
3633                yield();
3634        }
3635        V(this->lock);
3636}
3637
3638void main(Second* this) {
3639        P(this->lock);
3640        for(int i = 0; i < 10; i++) {
3641                sout | "Second : Suspend No." | i + 1 | endl;
3642                yield();
3643        }
3644}
3645
3646
3647int main(int argc, char* argv[]) {
3648        semaphore lock = { 0 };
3649        sout | "User main begin" | endl;
3650        {
3651                processor p;
3652                {
3653                        First  f = { &lock };
3654                        Second s = { &lock };
3655                }
3656        }
3657        sout | "User main end" | endl;
3658}
3659\end{cfa}
3660\caption{Simple Tasks}
3661\label{f:SimpleTasks}
3662\end{figure}
3663
3664
3665\begin{comment}
3666\begin{cfa}
3667type Adder = task {
3668        int *row;
3669        int size;
3670        int &subtotal;
3671}
3672\end{cfa}
3673
3674A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
3675A 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).
3676After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
3677All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
3678Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
3679(Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
3680\begin{cfa}
3681void ?{}(Adder &a, int r[], int s, int &st) { // constructor
3682        a.row = r;
3683        a.size = s;
3684        a.subtotal = st;
3685}
3686
3687// implicitly spawn thread and begin execution here
3688
3689void ?()(Adder &a) {
3690        int c;
3691        subtotal = 0;
3692        for (c=0; c<a.size; ++c) {
3693        subtotal += row[c];
3694        }
3695}
3696
3697int main() {
3698        const int rows = 100, cols = 1000000;
3699        int matrix[rows][cols];
3700        int subtotals[rows];
3701        int total = 0;
3702        int r;
3703
3704        { // create a new scope here for our adders
3705        Adder adders[rows];
3706        // read in the matrix
3707        ...
3708        for (r=0; r<rows; ++r) {
3709        // tasks are initialized on this thread
3710        Adders[r] = {matrix[r], cols, subtotals[r]};
3711        Adders[r](); // spawn thread and begin execution
3712        }
3713        } // adders go out of scope; block here until they all finish
3714        total += subtotals[r];
3715        printf(.total is %d\n., total);
3716}
3717\end{cfa}
3718
3719\subsection{Cooperative Scheduling}
3720
3721Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
3722In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
3723Places 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.
3724This 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.
3725For example, the code below defines a monitor that maintains a generic list.
3726When 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.
3727Similarly, 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.
3728
3729\begin{cfa}
3730// type T is used as a generic type for all definitions inside
3731// the curly brackets
3732
3733generic(type T) {
3734        type Channel = monitor {
3735        List(T) list; // list is a simple generic list type
3736        };
3737
3738        T pop(mutex &Channel(T) ch) {
3739        if (ch.list.empty()) {
3740        // yield until push is called for this channel
3741        yield(push);
3742        }
3743        return ch.list.pop();
3744        }
3745
3746        void push(mutex &Channel(T)ch, T val) {
3747        if (ch.list.full()) {
3748        // yield until pop is called for this channel
3749        yield(pop);
3750        }
3751        ch.list.push(val);
3752        }
3753}
3754\end{cfa}
3755
3756A task can also yield indefinitely by calling yield with no arguments.
3757This will tell the scheduler to yield this task until it is resumed by some other task.
3758A task can resume another task by using its functional call operator.
3759The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
3760
3761\begin{cfa}
3762type Ping = task {
3763        Pong *partner;
3764};
3765
3766void ?{}(Ping &p, Pong *partner = 0) {
3767        p.partner = partner;
3768}
3769
3770void ?()(Ping &p) {
3771        for(;;) { // loop forever
3772        printf(.ping\n.);
3773        partner(); // resumes the partner task
3774        yield(); // yields this task
3775        }
3776}
3777
3778type Pong = task {
3779        Ping *partner;
3780};
3781
3782void ?{}(Pong &p, Ping *partner = 0) {
3783        p.partner = partner;
3784}
3785
3786void ?()(Pong &p) {
3787        for(;;) { // loop forever
3788        yield(); // yields this task
3789        printf(.pong/n.);
3790        partner(); // resumes the partner task
3791        }
3792}
3793
3794void main() {
3795        Ping ping; // allocate ping
3796        Pong pong{ping}; // allocate, initialize, and start pong
3797        Ping{pong}; // initialize and start ping
3798}
3799\end{cfa}
3800
3801The same functionality can be accomplished by providing functions to be called by the partner task.
3802\begin{cfa}
3803type Pingpong = task {
3804        String msg;
3805        Pingpong *partner;
3806};
3807
3808void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
3809        p.msg = msg;
3810        p.partner = partner;
3811}
3812
3813void ?()(Pingpong &p) {
3814        for(;;) {
3815        yield(go);
3816        }
3817}
3818
3819void go(Pingpong &p) {
3820        print(.%(p.msg)\n.);
3821        go(p.partner);
3822}
3823
3824void main() {
3825        Pingpong ping = {.ping.};
3826        Pingpong pong = {.pong., ping};
3827        ping.partner = pong;
3828        go(ping);
3829}
3830\end{cfa}
3831\end{comment}
3832
3833
3834\begin{comment}
3835\section{Modules and Packages }
3836
3837High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed.
3838\CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time.
3839
3840There are two levels of encapsulation in \CFA, module and package.
3841A 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}.
3842A module forms a namespace to limit the visibility and prevent naming conflicts of variables.
3843Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed.
3844
3845A package is a physical grouping of one or more modules that is used for code distribution and version management.
3846Package is also the level of granularity at which dependences are managed.
3847A package is similar to the Crate in \Index*{Rust}.
3848
3849
3850\subsection{No Declarations, No Header Files}
3851
3852In 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.
3853Header files and a preprocessor are normally used to avoid repeating code.
3854Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work.
3855Instead of following this model, the \CFA tools can extract all of the same information from the code automatically.
3856This 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.
3857In 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.
3858This 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.
3859
3860In \CFA, multiple definitions are not necessary.
3861Within a module, all of the module's global definitions are visible throughout the module.
3862For example, the following code compiles, even though �isOdd� was not declared before being called:
3863\begin{cfa}
3864bool isEven(unsigned int x) {
3865        if (x == 0) return true;
3866        else return !isOdd(x);
3867}
3868
3869bool isOdd(unsigned int x) {
3870        if (x == 1) return true;
3871        else return !isEven(x - 2);
3872}
3873\end{cfa}
3874
3875Header files in C are used to expose the declarations from a library, so that they can be used externally.
3876With \CFA, this functionality is replaced with module exports, discussed below.
3877When 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.
3878
3879In 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).
3880
3881
3882\subsection{Modules}
3883
3884A 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.
3885These modules can then be easily shared and reused in multiple projects.
3886As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces.
3887
3888\CFA adds the following keywords to express the module systems: module, export, import, as.
3889
3890
3891\subsubsection{Module Declaration}
3892
3893The syntax to declare a module is module moduleName;.
3894
3895The module declaration must be at the beginning of a file, and each file can only belong to one module.
3896If there is no module declaration at the beginning of a file, the file belongs to the global module.
3897A module can span several files.
3898By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation.
3899
3900The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship.
3901For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container.
3902
3903Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface.
3904A method, a global variable or a type can be declared as a module interface.
3905Types defined in a module and referenced by an exported function or a variable must be exported, too.
3906
3907The following code is a simple module declaration example.
3908\begin{cfa}
3909module M;
3910
3911//visible outside module M
3912
3913export int f(int i) { return i + 1; }
3914export double aCounter;
3915
3916//not visible outside module M
3917
3918int g(int i) { return i - 1; }
3919
3920double bCounter;
3921\end{cfa}
3922
3923export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module.
3924
3925
3926\subsubsection{Module Import}
3927
3928The syntax to import a module is import moduleName; or import moduleName as anotherName;.
3929One package cannot be imported with both of the two types of syntax in one file.
3930A package imported in one file will only be visible in this file.
3931For example, two files, A and B belong to the same module.
3932If file A imports another module, M, the exported names in M are not visible in file B.
3933
3934All of the exported names are visible in the file that imports the module.
3935The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo).
3936If 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(...);).
3937The 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.
3938Conflicts in namespaces will be reported by the compiler.
3939The second method can be used to solve conflicting name problems.
3940The following code snippets show the two situations.
3941
3942\begin{cfa}
3943module util/counter;
3944export int f(int i) { return i+1; }
3945
3946import util/counter;
3947
3948int main() {
3949        return counter.f(200); // f() from the package counter
3950}
3951
3952import util/counter as ct;
3953int main() {
3954        return ct.f(200); // f() from the package counter
3955}
3956\end{cfa}
3957
3958
3959Additionally, 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.
3960
3961\begin{cfa}
3962module M1;
3963export int f(int i) { return i+1;} // visible outside
3964
3965int g(int i) { return i-1;} // not visible outside
3966
3967module M2;
3968int f(int i) { return i * 2; } // not visible outside
3969export int g(int g) { return i / 2; } // visible outside
3970
3971import M1 as .;
3972
3973import M2 as .;
3974
3975
3976int main() {
3977        return f(3) + g(4); //f() from M1 and g() from M2;
3978}
3979\end{cfa}
3980
3981
3982\subsubsection{Sub-Module and Module Aggregation}
3983
3984Several modules can be organized in a parent module and sub-modules relationship.
3985The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship.
3986For example, std/vector and std/io are sub-modules of module std.
3987The 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
3988not implicitly exported in the parent module.
3989
3990Aggregation is a mechanism to support components and simplified importing.
3991The mechanism is not based on naming but based on manual declaration.
3992For example, the following is the aggregated sequence module.
3993The export {...} is syntactic sugar for many lines of export module aModule;.
3994If an aggregated module is imported, all the included modules in the aggregation are imported.
3995
3996\begin{cfa}
3997module std/sequence;
3998
3999export {
4000        module std/vector;
4001        module std/list;
4002        module std/array;
4003        module std/deque;
4004        module std/forward_list;
4005        module std/queue;
4006        module std/stack;
4007};
4008\end{cfa}
4009
4010After importing the aggregated module, each individual name is still contained in the original name space.
4011For 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.
4012
4013
4014\subsubsection{Import from Repository}
4015
4016When 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).
4017The tools also support retrieving modules of a package from external repositories.
4018See Listing 40: Package directory structure
4019
4020
4021\subsubsection{Package Import}
4022
4023Because 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.
4024In 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;
4025or 2) Adding the package dependence into the current project's Do.prj.
4026More details about locating a module in a package are explained in the next section.
4027
4028
4029\subsubsection{Package Versioning}
4030
4031A package must have a version number.
4032The version number is a string.
4033For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
4034By convention, a package is stored in a directory named packageName-packageVersion.
4035For example, the util package with version 1.1 is stored in a directory named util-1.1.
4036
4037The project description file can optionally specify the version of the package used in the current project.
4038If 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.
4039The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
4040
4041
4042\subsection{Module and Package Organization}
4043
4044\CFA has two level of encapsulations, module and package.
4045This section explains the object model of modules, packages and other language concepts.
4046It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
4047
4048
4049\subsubsection{Object Model}
4050
4051There are several concepts in Do.
4052\begin{itemize}
4053\item
4054File: a \CFA source file
4055\item
4056Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
4057\item
4058Package: a container to organize modules for distribution; It has attributes like name, author,
4059version, dependences, etc.
4060\item
4061Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
4062\end{itemize}
4063
4064The following rules summarize the object model of all the above concepts:
4065\begin{itemize}
4066\item
4067A module contains one or more files
4068\begin{itemize}
4069\item
4070One file can only belong to one module
4071\item
4072A module has its name and interfaces exported
4073\item
4074A file without a module declaration at the beginning belongs to the global module
4075\item
4076\end{itemize}
4077
4078\item
4079A package contains one or more modules
4080\begin{itemize}
4081\item
4082A package has additional meta info described in Do.prj file
4083\item
4084A package may be dependent on other packages.
4085\end{itemize}
4086
4087\item
4088A project contains one or more modules in its source code
4089\begin{itemize}
4090\item
4091A project has additional meta info described in Do.prj file
4092\item
4093A project may be dependent on other packages
4094\item
4095A project can be transformed into a package for distribution
4096\item
4097A project can generate one or more executable binaries
4098\end{itemize}
4099\end{itemize}
4100
4101
4102\subsubsection{Module File Organization}
4103
4104The rules of this section are the conventions to organize module files in one package.
4105
4106The file location of a module in a package must match the module/submodule naming hierarchy.
4107The names separated by slash "/" must match the directory levels.
4108If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
4109The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
4110
4111Here is an example of a package, util.
4112\begin{cfa}
4113+ util
4114Do.prj #package description file
4115        heap.do #Case 1: module heap;
4116        list.do #Case 1: mdoule list;
4117        ring.do #Case 1: module ring;
4118        + string #Case 2
4119        impl1.do #module string;
4120        + std
4121        vector.do
4122        list.do
4123        + array #Case 3
4124        array1.do #module std/array;
4125        array2.do #module std/array;
4126        sequence.do #Case 4, module std/sequence;
4127        test.do #Case 5
4128\end{cfa}
4129
4130\begin{itemize}
4131\item
4132Case 1: Each individual file implements a module
4133\item
4134Case 2: Put the implementation of a module under the sub-directory, but there is only one file
4135\item
4136Case 3: Put the implementation of a module under the sub-directory; There are several files to
4137implement one module
4138\item
4139Case 4: One file to express one aggregation
4140\item
4141Case 5: The file does not belong to any module; It is used for testing purpose
4142\end{itemize}
4143
4144The example only uses source code, ".do" files, to show the module file organization.
4145Other module packaging formats, like binary, must also follow the same rules.
4146
4147
4148\subsection{Module File Format}
4149
4150\CFA supports different types of module file formats.
4151
4152\begin{itemize}
4153\item
4154Pure source code format: The files should be organized following the previous section's definition.
4155\item
4156IR format (TBD): The \CFA compiler IR format, similar to the source code format
4157\item
4158Binary format, including ".a" static library or ".so" dynamic linkage library
4159\begin{itemize}
4160\item
4161The file's name must match the right level's module name defined in the previous section
4162\item
4163E.g. "util.so" includes all modules for the package util.
4164\item
4165E.g. "string.so" under the package directory to include files belonging to "module string;"
4166\end{itemize}
4167\item.
4168Archive format
4169\begin{itemize}
4170\item
4171The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
4172\item
4173E.g. "util.dar" is the whole package for util package including the package direction file
4174\end{itemize}
4175\item
4176Hybrid format
4177\begin{itemize}
4178\item
4179A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
4180\item
4181The only limitation is that the names of the files must match the module location names defined in previous section
4182\end{itemize}
4183\end{itemize}
4184Package and Module Locating and the \CFA Language Tooling documentation for more details.
4185
4186
4187\subsection{Packages}
4188
4189A package is synonymous with a library in other languages.
4190The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management.
4191A package is a physical grouping of one or more modules in a directory (an archive file for a directory).
4192The 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.
4193
4194
4195\subsubsection{Package Definition}
4196
4197A package is defined by putting a project description file, Do.prj, with one or more modules into a directory.
4198This project description file contains the package's meta data, including package name, author, version, dependences, etc.
4199It should be in the root of the package directory.
4200
4201The modules in the package could be either source code, or compiled binary format.
4202The location of the module files should follow the module name's path.
4203
4204Here is a simple example of the directory structure of a package, core.
4205It contains a module std and several sub-modules under std.
4206\begin{cfa}
4207+ core
4208        Do.prj
4209        + std
4210        + io
4211        file.do # module std/io/file;
4212        network.do #module std/io/network;
4213        + container
4214        vector.do #module std/container/vector;
4215        list.do #module std/container/list;
4216\end{cfa}
4217
4218
4219\subsubsection{Package Import}
4220
4221Because 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.
4222In 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.
4223More details about locating a module in a package are explained in the next section.
4224
4225
4226\subsubsection{Package Versioning}
4227
4228A package must have a version number.
4229The version number is a string.
4230For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
4231By convention, a package is stored in a directory named packageName-packageVersion.
4232For example, the util package with version 1.1 is stored in a directory named util-1.1.
4233
4234The project description file can optionally specify the version of the package used in the current project.
4235If 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.
4236The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
4237
4238
4239\subsection{Module and Package Organization}
4240
4241\CFA has two level of encapsulations, module and package.
4242This section explains the object model of modules, packages and other language concepts.
4243It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
4244
4245
4246\subsubsection{Object Model}
4247
4248There are several concepts in Do.
4249\begin{itemize}
4250\item
4251File: a \CFA source file
4252\item
4253Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
4254\item
4255Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc.
4256\item
4257Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
4258\end{itemize}
4259
4260The following rules summarize the object model of all the above concepts:
4261\begin{itemize}
4262\item
4263A module contains one or more files
4264\begin{itemize}
4265\item
4266One file can only belong to one module
4267\item
4268A module has its name and interfaces exported
4269\item
4270A file without a module declaration at the beginning belongs to the global module
4271\end{itemize}
4272\item
4273A package contains one or more modules
4274\begin{itemize}
4275\item
4276A package has additional meta info described in Do.prj file
4277\item
4278A package may be dependent on other packages.
4279\end{itemize}
4280\item
4281A project contains one or more modules in its source code
4282\begin{itemize}
4283\item
4284A project has additional meta info described in Do.prj file
4285\item
4286A project may be dependent on other packages
4287\item
4288A project can be transformed into a package for distribution
4289\item
4290A project can generate one or more executable binaries
4291\end{itemize}
4292\end{itemize}
4293
4294
4295\subsubsection{Module File Organization}
4296
4297The rules of this section are the conventions to organize module files in one package.
4298
4299The file location of a module in a package must match the module/submodule naming hierarchy.
4300The names separated by slash "/" must match the directory levels.
4301If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
4302The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
4303
4304Here is an example of a package, util.
4305\begin{cfa}
4306+ util
4307        Do.prj #package description file
4308        heap.do #Case 1: module heap;
4309        list.do #Case 1: mdoule list;
4310        ring.do #Case 1: module ring;
4311        + string #Case 2
4312        impl1.do #module string;
4313        + std
4314        vector.do
4315        list.do
4316        + array #Case 3
4317        array1.do #module std/array;
4318        array2.do #module std/array;
4319        sequence.do #Case 4, module std/sequence;
4320        test.do #Case 5
4321\end{cfa}
4322
4323
4324\begin{itemize}
4325\item
4326Case 1: Each individual file implements a module
4327\item
4328Case 2: Put the implementation of a module under the sub-directory, but there is only one file
4329\item
4330Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module
4331\item
4332Case 4: One file to express one aggregation
4333\item
4334Case 5: The file does not belong to any module; It is used for testing purpose
4335\end{itemize}
4336
4337The example only uses source code, ".do" files, to show the module file organization.
4338Other module packaging formats, like binary, must also follow the same rules.
4339
4340
4341\subsubsection{Module File Format}
4342
4343\CFA supports different types of module file formats.
4344
4345\begin{itemize}
4346\item
4347Pure source code format: The files should be organized following the previous section's definition.
4348\item
4349IR format (TBD): The \CFA compiler IR format, similar to the source code format
4350\item
4351Binary format, including ".a" static library or ".so" dynamic linkage library
4352\begin{itemize}
4353\item
4354The file's name must match the right level's module name defined in the previous section
4355\item
4356E.g. "util.so" includes all modules for the package util.
4357\item
4358E.g. "string.so" under the package directory to include files belonging to "module string;"
4359\end{itemize}
4360\item
4361Archive format
4362\begin{itemize}
4363\item
4364The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
4365\item
4366E.g. "util.dar" is the whole package for util package including the package direction file
4367\end{itemize}
4368\item
4369Hybrid format
4370\begin{itemize}
4371\item
4372A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
4373\item
4374The only limitation is that the names of the files must match the module location names defined in previous section
4375\end{itemize}
4376\end{itemize}
4377
4378
4379\subsection{Package and Module Locating}
4380
4381The 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.
4382If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries.
4383
4384When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order:
4385
4386\begin{enumerate}
4387\item
4388This source file's directory tree, which is typically the project's src directory
4389\item
4390All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory
4391\item
4392The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable
4393\item
4394The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory
4395\item
4396If 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
4397\end{enumerate}
4398
4399The module found first in a package will shadow the modules with the same name in the later packages in the search sequence.
4400
4401
4402\subsubsection{Dependent Package}
4403
4404Dependent packages are those packages containing modules that the current project's source code will import from.
4405Dependent packages are defined implicitly or explicitly in one \CFA project.
4406All of the packages under the current project's pkg directory are implicitly dependent packages.
4407For others, the dependent packages must be defined in the project's Do.prj file.
4408
4409
4410\subsubsection{Package and Module Locating Example}
4411
4412\begin{cfa}
4413# A project's source code tree
4414
4415--------------------------------------
4416
4417+ testProject
4418        Do.prj
4419        + src
4420        main.do
4421        + pkg
4422        + security-1.1
4423        Do.prj
4424        security.do #module security
4425
4426--------------------------------------
4427
4428# Do.prj
4429
4430--------------------------------------
4431
4432[dependences]
4433std
4434util = "0.2"
4435
4436--------------------------------------
4437
4438# main.do
4439
4440---------------------------------------
4441
4442import security;
4443import std/vector;
4444import container;
4445
4446----------------------------------------
4447\end{cfa}
4448
4449
4450\begin{cfa}
4451# pkg directory's source code tree
4452
4453-----------------------------------------
4454
4455+ pkg
4456        + std-1.0
4457        Do.prj
4458        vector.do #module std/vector;
4459        queue.do #module std/queue;
4460        + std-1.1
4461        Do.prj
4462        vector.do #module std/vector;
4463        queue.do #module std/queue;
4464        list.do #module std/list;
4465        + util-0.1
4466        Do.prj
4467        container.do #module container;
4468        + security-1.0
4469        security.do #module security;
4470------------------------------------------
4471\end{cfa}
4472
4473
4474During the compiling of main.do file import security;
4475The security module appears in both the local security-1.1 package, and the global security-1.0 package.
4476According to the locating sequence, the local security module in security-1.1 will be used.
4477And because the security-1.1 package is under local's pkg directory.
4478No dependence description is required in the project Do.prj file.
4479
4480import std/vector;
4481
4482The 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.
4483
4484import container;
4485
4486The 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.
4487The builder tool then will try to retrieve it from the web and store it in the global pkg directory.
4488After that, the container module from the newly downloaded package will be used in the compilation.
4489\end{comment}
4490
4491
4492\section{Comparison with Other Languages}
4493
4494\CFA is one of many languages that attempts to improve upon C.
4495In developing \CFA, many other languages were consulted for ideas, constructs, and syntax.
4496Therefore, it is important to show how these languages each compare with Do.
4497In 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}.
4498
4499
4500\begin{comment}
4501\subsection[Comparing Key Features of CFA]{Comparing Key Features of \CFA}
4502
4503
4504{% local change to lstlising to reduce font size
4505
4506
4507\lstset{basicstyle=\linespread{0.9}\sf\relsize{-2}}
4508
4509
4510\subsubsection{Constructors and Destructors}
4511
4512\begin{flushleft}
4513\begin{tabular}{@{}l|l|l|l@{}}
4514\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4515\hline
4516\begin{cfa}
4517struct Line {
4518        float lnth;
4519}
4520// default constructor
4521void ?{}( Line * l ) {
4522        l->lnth = 0.0;
4523        sout | "default" | endl;
4524}
4525
4526
4527// constructor with length
4528void ?{}( Line * l, float lnth ) {
4529        l->lnth = lnth;
4530        sout | "lnth" | l->lnth | endl;
4531
4532}
4533
4534// destructor
4535void ^?() {
4536        sout | "destroyed" | endl;
4537        l.lnth = 0.0;
4538}
4539
4540// usage
4541Line line1;
4542Line line2 = { 3.4 };
4543\end{cfa}
4544&
4545\begin{lstlisting}[language=C++]
4546class Line {
4547        float lnth;
4548
4549        // default constructor
4550        Line() {
4551                cout << "default" << endl;
4552                lnth = 0.0;
4553        }
4554
4555
4556        // constructor with lnth
4557        Line( float l ) {
4558                cout << "length " << length
4559                         << endl;
4560                length = l;
4561        }
4562
4563        // destructor
4564        ~Line() {
4565                cout << "destroyed" << endl;
4566                length = 0.0;
4567        }
4568}
4569// usage
4570Line line1;
4571Line line2( 3.4 );
4572\end{lstlisting}
4573&
4574\begin{lstlisting}[language=Golang]
4575type Line struct {
4576        length float32
4577}
4578// default constructor
4579func makeLine() Line {
4580        fmt.PrintLn( "default" )
4581        return Line{0.0}
4582}
4583
4584
4585// constructor with length
4586func makeLine( length float32 ) Line {
4587        fmt.Printf( "length %v", length )
4588
4589        return Line{length}
4590}
4591
4592// no destructor
4593
4594
4595
4596
4597
4598// usage
4599line1 := makeLine()
4600line2 := makeLine( 3.4 )
4601\end{lstlisting}
4602&
4603\begin{cfa}
4604struct Line {
4605        length: f32
4606}
4607// default constructor
4608impl Default for Line {
4609        fn default () -> Line {
4610                println!( "default" );
4611                Line{ length: 0.0 }
4612        }
4613}
4614// constructor with length
4615impl Line {
4616        fn make( len: f32 ) -> Line {
4617                println!( "length: {}", len );
4618                Line{ length: len }
4619        }
4620}
4621// destructor
4622impl Drop for Line {
4623        fn drop( &mut self ) {
4624                self.length = 0.0
4625        }
4626}
4627// usage
4628let line1:Line = Default::default();
4629Line line2( 3.4 );
4630\end{cfa}
4631\end{tabular}
4632\end{flushleft}
4633
4634
4635\subsubsection{Operator Overloading}
4636
4637\begin{flushleft}
4638\begin{tabular}{@{}l|l|l|l@{}}
4639\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4640\hline
4641\begin{cfa}
4642struct Cpx {
4643        double re, im;
4644};
4645// overload addition operator
4646Cpx ?+?( Cpx l, const Cpx r ) {
4647        return (Cpx){l.re+l.im, l.im+r.im};
4648}
4649Cpx a, b, c;
4650c = a + b;
4651\end{cfa}
4652&
4653\begin{cfa}
4654struct Cpx {
4655        double re, im;
4656};
4657// overload addition operator
4658Cpx operator+( Cpx l, const Cpx r ) {
4659        return (Cpx){l.re+l.im, l.im+r.im};
4660}
4661Cpx a, b, c;
4662c = a + b;
4663\end{cfa}
4664&
4665\begin{cfa}
4666// no operator overloading
4667
4668
4669
4670
4671
4672
4673
4674\end{cfa}
4675&
4676\begin{cfa}
4677struct Cpx {
4678        re: f32,
4679        im: f32
4680}
4681// overload addition operator
4682impl Add for Cpx {
4683        type Output = Cpx
4684        fn add(self, r: Cpx) -> Cpx {
4685                let mut res = Cpx{re: 0.0, im: 0.0};
4686                res.re = self.re + r.re;
4687                res.im = self.im + r.im;
4688                return res
4689        }
4690}
4691let (a, b, mut c) = ...;
4692c = a + b
4693\end{cfa}
4694\end{tabular}
4695\end{flushleft}
4696
4697
4698\subsubsection{Calling C Functions}
4699
4700\begin{flushleft}
4701\begin{tabular}{@{}l|l|l@{}}
4702\multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}   \\
4703\hline
4704\begin{cfa}[boxpos=t]
4705extern "C" {
4706#include <sys/types.h>
4707#include <sys/stat.h>
4708#include <unistd.h>
4709}
4710size_t fileSize( const char *path ) {
4711        struct stat s;
4712        stat(path, &s);
4713        return s.st_size;
4714}
4715\end{cfa}
4716&
4717\begin{cfa}[boxpos=t]
4718/*
4719#cgo
4720#include <sys/types.h>
4721#include <sys/stat.h>
4722#include <unistd.h>
4723*/
4724import "C"
4725import "unsafe"
4726
4727func fileSize(path string) C.size_t {
4728        var buf C.struct_stat
4729        c_string := C.CString(path)
4730        C.stat(p, &buf)
4731        C.free(unsafe.Pointer(c_string))
4732        return buf._st_size
4733}
4734\end{cfa}
4735&
4736\begin{cfa}[boxpos=t]
4737use libc::{c_int, size_t};
4738// translated from sys/stat.h
4739#[repr(C)]
4740struct stat_t {
4741        ...
4742        st_size: size_t,
4743        ...
4744}
4745#[link(name = "libc")]
4746extern {
4747        fn stat(path: *const u8,
4748        buf: *mut stat_t) -> c_int;
4749}
4750fn fileSize(path: *const u8) -> size_t
4751{
4752        unsafe {
4753                let mut buf: stat_t = uninit();
4754                stat(path, &mut buf);
4755                buf.st_size
4756        }
4757}
4758\end{cfa}
4759\end{tabular}
4760\end{flushleft}
4761
4762
4763\subsubsection{Generic Functions}
4764
4765\begin{flushleft}
4766\begin{tabular}{@{}l|l|l|l@{}}
4767\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4768\hline
4769\begin{cfa}
4770generic(type T, type N |
4771        { int ?<?(N, N); })
4772T *maximize(N (*f)(const T&),
4773        int n, T *a) {
4774        T *bestX = NULL;
4775        N bestN;
4776        for (int i = 0; i < n; i++) {
4777        N curN = f(a[i]);
4778        if (bestX == NULL ||
4779        curN > bestN) {
4780        bestX = &a[i]; bestN = curN;
4781        }
4782        }
4783        return bestX;
4784}
4785
4786string *longest(int n, string *p)
4787{
4788        return maximize(length, n, p);
4789}
4790\end{cfa}
4791&
4792\begin{cfa}
4793template<typename T, typename F>
4794T *maximize(const F &f,
4795        int n, T *a) {
4796        typedef decltype(f(a[0])) N;
4797        T *bestX = NULL;
4798        N bestN;
4799        for (int i = 0; i < n; i++) {
4800        N curN = f(a[i]);
4801        if (bestX == NULL || curN > bestN)
4802        {
4803        bestX = &a[i]; bestN = curN;
4804        }
4805        }
4806        return bestX;
4807}
4808
4809string *longest(int n, string *p) {
4810        return maximize(
4811        [](const string &s) {
4812        return s.length();
4813        }, n, p);
4814}
4815\end{cfa}
4816&
4817\begin{cfa}
4818// Go does not support generics!
4819func maximize(
4820        gt func(interface{}, interface{}) bool,
4821        f func(interface{}) interface{},
4822        a []interface{}) interface{} {
4823        var bestX interface{} = nil
4824        var bestN interface{} = nil
4825        for _, x := range a {
4826        curN := f(x)
4827        if bestX == nil || gt(curN, bestN)
4828        {
4829        bestN = curN
4830        bestX = x
4831        }
4832        }
4833        return bestX
4834}
4835
4836func longest(
4837        a []interface{}) interface{} {
4838        return maximize(
4839        func(a, b interface{}) bool {
4840        return a.(int) > b.(int) },
4841        func(s interface{}) interface{} {
4842        return len(s.(string)) },
4843        a).(string)
4844}
4845\end{cfa}
4846&
4847\begin{cfa}
4848use std::cmp::Ordering;
4849
4850fn maximize<N: Ord + Copy, T, F:
4851Fn(&T) -> N>(f: F, a: &Vec<T>) ->
4852Option<&T> {
4853        let mut best_x: Option<&T> = None;
4854        let mut best_n: Option<N> = None;
4855        for x in a {
4856        let n = f(x);
4857        if (match best_n { None => true,
4858        Some(bn) =>
4859        n.cmp(&bn) == Ordering::Greater })
4860        {
4861        best_x = Some(x);
4862        best_n = Some(n);
4863        }
4864        }
4865        return best_x
4866}
4867
4868fn longest(a: &Vec<String>) ->
4869        Option<&String> {
4870        return
4871        maximize(|x: &String| x.len(), a)
4872}
4873\end{cfa}
4874\end{tabular}
4875\end{flushleft}
4876
4877
4878\subsubsection{Modules / Packages}
4879
4880\begin{cfa}
4881\CFA
4882\CC
4883
4884
4885module example/M;
4886
4887export int inc(int val) {
4888        return val + 1;
4889}
4890
4891
4892
4893
4894--------------------------------------
4895//Use the module in another file
4896import example/M;
4897int main() {
4898        print(M.inc(100));
4899        return 0;
4900}
4901// Using \CC17 module proposal
4902
4903module example.M;
4904
4905export {
4906        int inc(int val);
4907}
4908
4909int inc(inv val) {
4910        return val + 1;
4911}
4912--------------------------------------
4913// Use the module in another file
4914import example.M;
4915int main() {
4916        cout << inc(100) << endl;
4917        return 0;
4918}
4919
4920Go
4921Rust
4922package example/M;
4923
4924func Inc(val int32) int32 {
4925        // Capitalization indicates exported
4926        return val + 100
4927}
4928
4929
4930--------------------------------------
4931//Use the package in another file
4932package main
4933import .fmt.
4934import "example/M"
4935
4936func main() int32 {
4937        fmt.Printf(.%v., M.Inc(100))
4938}
4939pub mod example {
4940        pub mod M {
4941        pub inc(val i32) -> i32 {
4942        return val + 100;
4943        }
4944        }
4945}
4946
4947--------------------------------------
4948//Use the module in another file
4949use example::M;
4950
4951
4952
4953fn main() {
4954        println!(.{}., M::inc(100));
4955}
4956\end{cfa}
4957
4958
4959\subsubsection{Parallel Tasks}
4960
4961\begin{flushleft}
4962\begin{tabular}{@{}l|l|l|l@{}}
4963\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4964\hline
4965\begin{cfa}
4966task Nonzero {
4967        int *data;
4968        int start;
4969        int end;
4970        int* res;
4971};
4972
4973void ?{}(Nonzero &a, int d[], int s,
4974        int e, int* subres) {
4975        // constructor
4976        a.data = d;
4977        a.start = s;
4978        a.end = e;
4979        a.res = subres;
4980}
4981
4982// implicitly spawn thread here
4983void ?()(NonzeroCounter &a) {
4984        int i;
4985        int nonzero = 0;
4986        for (i=start; c<end; ++i) {
4987        if(a.data[i]!=0){ nonzero++;}
4988        }
4989        *a.res = nonzero;
4990}
4991
4992int main() {
4993        int sz = ...
4994        int data[sz] = ...;
4995        int r1 = 0, r2=0;
4996        int res;
4997        { // create a scope for Nonzero
4998        Nonzero n1{data, 0, sz/2, &n1};
4999        Nonzero n2{data, sz/2, sz, &n2};
5000        n1();//spawn
5001        n2();//spawn
5002        }
5003        res = r1+r2;
5004        return res;
5005}
5006\end{cfa}
5007&
5008\begin{cfa}
5009#include <thread>
5010#include <mutex>
5011
5012std::mutex m;
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025void task(const vector<int>&v,
5026        int* res, size_t s,
5027        size_t e) {
5028        int non_zero = 0;
5029        for(size_t i = s; i < e; ++i){
5030        if(v[i]!=0) { non_zero++;}
5031        }
5032        std::unique_lock<mutex> lck {m};
5033        *res += non_zero;
5034}
5035
5036int main() {
5037        vector<int> data = ...; //data
5038        int res = 0;
5039        std::thread t1 {task, ref(data),
5040        &res, 0,
5041        data.size()/2};
5042        std::thread t2 {task, ref(data),
5043        &res, data.size()/2,
5044        data.size()};
5045        t1.join();
5046        t2.join();
5047        return res;
5048}
5049\end{cfa}
5050&
5051\begin{cfa}
5052package main
5053
5054import "fmt"
5055
5056func nonzero(data []int, c chan int) {
5057        nz := 0
5058        for _, v:=range data {
5059        if(v!=0) { nz := nz+1 }
5060        }
5061        c <- nz
5062}
5063
5064func main() {
5065        sz := ...
5066        data := make([]int, sz)
5067        ... // data init
5068        go nonzero(data[:len(data)/2], c)
5069        go nonzero(data[len(data)/2:], c)
5070        n1, n2 := <-c, <-c
5071        res := n1 + n2
5072        fmt.Println(res)
5073}
5074\end{cfa}
5075&
5076\begin{cfa}
5077use std::thread;
5078use std::sync:mpsc::channel;
5079
5080fn main() {
5081        let sz = ...;
5082        let mut data:Vec<i32> =
5083        Vec::with_capacity(sz as usize);
5084        ... //init data
5085        let (tx, rx) = channel();
5086        for i in 0..1 {
5087        let tx = tx.clone();
5088        let data = data.clone()
5089        thread::spawn(move|| {
5090        let mut nz := 0;
5091        let mut s = 0;
5092        let mut e = sz / 2;
5093        if i == 1 {
5094        s = sz/2;
5095        e = data.len();
5096        }
5097        for i in s..(e - 1) {
5098        if data[i] != 0 (
5099        nz = nz + 1
5100        }
5101        }
5102        tx.send(nz).unwrap();
5103        });
5104        }
5105        let res = rx.recv().unwrap() +
5106        rx.recv().unwrap();
5107        println!(.{}., res);
5108}
5109\end{cfa}
5110\end{tabular}
5111\end{flushleft}
5112
5113}% local change to lstlising to reduce font size
5114
5115
5116\subsection{Summary of Language Comparison}
5117\end{comment}
5118
5119
5120\subsection[C++]{\CC}
5121
5122\Index*[C++]{\CC{}} is a general-purpose programming language.
5123It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia)
5124
5125The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do.
5126\CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data.
5127\CFA uses modules instead to perform these same tasks.
5128Classes in \CC also enable inheritance among types.
5129Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility.
5130There 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).
5131
5132Overloading 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.
5133References and exceptions in \CFA are heavily based on the same features from \CC.
5134The mechanism for interoperating with C code in \CFA is also borrowed from \CC.
5135
5136Both \CFA and \CC provide generics, and the syntax is quite similar.
5137The 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.
5138This means that a generic function can be defined in a compiled library, and still be used as expected from source.
5139
5140
5141\subsection{Go}
5142
5143\Index*{Go}, also commonly referred to as golang, is a programming language developed at Google in 2007 [.].
5144It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type
5145safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia)
5146
5147Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned.
5148Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction.
5149Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse.
5150Both 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.
5151
5152Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks.
5153\CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection.
5154This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead.
5155
5156
5157\subsection{Rust}
5158
5159\Index*{Rust} is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research.
5160It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles.
5161
5162The primary focus of Rust is in safety, especially in concurrent programs.
5163To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety.
5164This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead.
5165
5166Aside from those key differences, Rust and \CFA also have several similarities.
5167Both languages support no overhead interoperability with C and have minimal runtimes.
5168Both languages support inheritance and polymorphism through the use of interfaces (traits).
5169
5170
5171\subsection{D}
5172
5173The \Index*{D} programming language is an object-oriented, imperative, multi-paradigm system programming
5174language created by Walter Bright of Digital Mars and released in 2001. [.]
5175Though 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.
5176
5177D and \CFA both start with C and add productivity features.
5178The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces.
5179D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces.
5180Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates.
5181D does not have any built-in concurrency constructs in the
5182language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency.
5183
5184
5185\appendix
5186
5187
5188\section{Syntax Ambiguities}
5189
5190C has a number of syntax ambiguities, which are resolved by taking the longest sequence of overlapping characters that constitute a token.
5191For example, the program fragment �x+++++y� is parsed as \lstinline[showspaces=true]@x ++ ++ + y@ because operator tokens �++� and �+� overlap.
5192Unfortunately, the longest sequence violates a constraint on increment operators, even though the parse \lstinline[showspaces=true]@x ++ + ++ y@ might yield a correct expression.
5193Hence, C programmers are aware that spaces have to added to disambiguate certain syntactic cases.
5194
5195In \CFA, there are ambiguous cases with dereference and operator identifiers, \eg �int *?*?()�, where the string �*?*?� can be interpreted as:
5196\begin{cfa}
5197*?�\color{red}\textvisiblespace�*?              �\C{// dereference operator, dereference operator}
5198*�\color{red}\textvisiblespace�?*?              �\C{// dereference, multiplication operator}
5199\end{cfa}
5200By default, the first interpretation is selected, which does not yield a meaningful parse.
5201Therefore, \CFA does a lexical look-ahead for the second case, and backtracks to return the leading unary operator and reparses the trailing operator identifier.
5202Otherwise a space is needed between the unary operator and operator identifier to disambiguate this common case.
5203
5204A similar issue occurs with the dereference, �*?(...)�, and routine-call, �?()(...)� identifiers.
5205The ambiguity occurs when the deference operator has no parameters:
5206\begin{cfa}
5207*?()�\color{red}\textvisiblespace...� ;
5208*?()�\color{red}\textvisiblespace...�(...) ;
5209\end{cfa}
5210requiring arbitrary whitespace look-ahead for the routine-call parameter-list to disambiguate.
5211However, the dereference operator \emph{must} have a parameter/argument to dereference �*?(...)�.
5212Hence, always interpreting the string �*?()� as \lstinline[showspaces=true]@* ?()@ does not preclude any meaningful program.
5213
5214The remaining cases are with the increment/decrement operators and conditional expression, \eg:
5215\begin{cfa}
5216i++?�\color{red}\textvisiblespace...�(...);
5217i?++�\color{red}\textvisiblespace...�(...);
5218\end{cfa}
5219requiring arbitrary whitespace look-ahead for the operator parameter-list, even though that interpretation is an incorrect expression (juxtaposed identifiers).
5220Therefore, it is necessary to disambiguate these cases with a space:
5221\begin{cfa}
5222i++�\color{red}\textvisiblespace�? i : 0;
5223i?�\color{red}\textvisiblespace�++i : 0;
5224\end{cfa}
5225
5226
5227\section{\CFA Keywords}
5228\label{s:CFAKeywords}
5229
5230\begin{quote2}
5231\begin{tabular}{llll}
5232\begin{tabular}{@{}l@{}}
5233_AT�                   \\
5234�catch�                 \\
5235�catchResume�   \\
5236�choose�                \\
5237�coroutine�             \\
5238�disable�               \\
5239\end{tabular}
5240&
5241\begin{tabular}{@{}l@{}}
5242�dtype�                 \\
5243�enable�                \\
5244�fallthrough�   \\
5245�fallthru�              \\
5246�finally�               \\
5247�forall�                \\
5248\end{tabular}
5249&
5250\begin{tabular}{@{}l@{}}
5251�ftype�                 \\
5252�lvalue�                \\
5253�monitor�               \\
5254�mutex�                 \\
5255�one_t�                 \\
5256�otype�                 \\
5257\end{tabular}
5258&
5259\begin{tabular}{@{}l@{}}
5260�throw�                 \\
5261�throwResume�   \\
5262�trait�                 \\
5263�try�                   \\
5264�ttype�                 \\
5265�zero_t�                \\
5266\end{tabular}
5267\end{tabular}
5268\end{quote2}
5269
5270
5271\section{Incompatible}
5272
5273The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{C++14}.
5274
5275
5276\begin{enumerate}
5277\item
5278\begin{description}
5279\item[Change:] add new keywords \\
5280New keywords are added to \CFA (see~\VRef{s:CFAKeywords}).
5281\item[Rationale:] keywords added to implement new semantics of \CFA.
5282\item[Effect on original feature:] change to semantics of well-defined feature. \\
5283Any \Celeven programs using these keywords as identifiers are invalid \CFA programs.
5284\item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism (see~\VRef{s:BackquoteIdentifiers}).
5285\item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare.
5286\end{description}
5287
5288\item
5289\begin{description}
5290\item[Change:] drop K\&R C declarations \\
5291K\&R declarations allow an implicit base-type of �int�, if no type is specified, plus an alternate syntax for declaring parameters.
5292\eg:
5293\begin{cfa}
5294x;                                                              �\C{// int x}
5295*y;                                                             �\C{// int *y}
5296f( p1, p2 );                                    �\C{// int f( int p1, int p2 );}
5297g( p1, p2 ) int p1, p2;                 �\C{// int g( int p1, int p2 );}
5298\end{cfa}
5299\CFA supports K\&R routine definitions:
5300\begin{cfa}
5301f( a, b, c )                                    �\C{// default int return}
5302        int a, b; char c                        �\C{// K\&R parameter declarations}
5303{
5304        ...
5305}
5306\end{cfa}
5307\item[Rationale:] dropped from \Celeven standard.\footnote{
5308At 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}}
5309\item[Effect on original feature:] original feature is deprecated. \\
5310Any old C programs using these K\&R declarations are invalid \CFA programs.
5311\item[Difficulty of converting:] trivial to convert to \CFA.
5312\item[How widely used:] existing usages are rare.
5313\end{description}
5314
5315\item
5316\begin{description}
5317\item[Change:] type of character literal �int� to �char� to allow more intuitive overloading:
5318\begin{cfa}
5319int rtn( int i );
5320int rtn( char c );
5321rtn( 'x' );                                             �\C{// programmer expects 2nd rtn to be called}
5322\end{cfa}
5323\item[Rationale:] it is more intuitive for the call to �rtn� to match the second version of definition of �rtn� rather than the first.
5324In particular, output of �char� variable now print a character rather than the decimal ASCII value of the character.
5325\begin{cfa}
5326sout | 'x' | " " | (int)'x' | endl;
5327x 120
5328\end{cfa}
5329Having to cast �'x'� to �char� is non-intuitive.
5330\item[Effect on original feature:] change to semantics of well-defined feature that depend on:
5331\begin{cfa}
5332sizeof( 'x' ) == sizeof( int )
5333\end{cfa}
5334no long work the same in \CFA programs.
5335\item[Difficulty of converting:] simple
5336\item[How widely used:] programs that depend upon �sizeof( 'x' )� are rare and can be changed to �sizeof(char)�.
5337\end{description}
5338
5339\item
5340\begin{description}
5341\item[Change:] make string literals �const�:
5342\begin{cfa}
5343char * p = "abc";                               �\C{// valid in C, deprecated in \CFA}
5344char * q = expr ? "abc" : "de"; �\C{// valid in C, invalid in \CFA}
5345\end{cfa}
5346The type of a string literal is changed from �[] char� to �const [] char�.
5347Similarly, the type of a wide string literal is changed from �[] wchar_t� to �const [] wchar_t�.
5348\item[Rationale:] This change is a safety issue:
5349\begin{cfa}
5350char * p = "abc";
5351p[0] = 'w';                                             �\C{// segment fault or change constant literal}
5352\end{cfa}
5353The same problem occurs when passing a string literal to a routine that changes its argument.
5354\item[Effect on original feature:] change to semantics of well-defined feature.
5355\item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to �char *�.
5356\item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare.
5357\end{description}
5358
5359\item
5360\begin{description}
5361\item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope:
5362\begin{cfa}
5363int i;                                                  �\C{// forward definition}
5364int *j = �&i�;                                  �\C{// forward reference, valid in C, invalid in \CFA}
5365int i = 0;                                              �\C{// definition}
5366\end{cfa}
5367is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed.
5368This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example,
5369\begin{cfa}
5370struct X { int i; struct X *next; };
5371static struct X a;                              �\C{// forward definition}
5372static struct X b = { 0, �&a� };        �\C{// forward reference, valid in C, invalid in \CFA}
5373static struct X a = { 1, &b };  �\C{// definition}
5374\end{cfa}
5375\item[Rationale:] avoids having different initialization rules for builtin types and user-defined types.
5376\item[Effect on original feature:] change to semantics of well-defined feature.
5377\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.
5378\item[How widely used:] seldom
5379\end{description}
5380
5381\item
5382\begin{description}
5383\item[Change:] have �struct� introduce a scope for nested types:
5384\begin{cfa}
5385enum �Colour� { R, G, B, Y, C, M };
5386struct Person {
5387        enum �Colour� { R, G, B };      �\C{// nested type}
5388        struct Face {                           �\C{// nested type}
5389                �Colour� Eyes, Hair;    �\C{// type defined outside (1 level)}
5390        };
5391        �.Colour� shirt;                        �\C{// type defined outside (top level)}
5392        �Colour� pants;                         �\C{// type defined same level}
5393        Face looks[10];                         �\C{// type defined same level}
5394};
5395�Colour� c = R;                                 �\C{// type/enum defined same level}
5396Person�.Colour� pc = Person�.�R;        �\C{// type/enum defined inside}
5397Person�.�Face pretty;                   �\C{// type defined inside}
5398\end{cfa}
5399In 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.
5400\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC{}}.
5401Nested types are not hoisted and can be referenced using the field selection operator ``�.�'', unlike the \CC scope-resolution operator ``�::�''.
5402\item[Rationale:] �struct� scope is crucial to \CFA as an information structuring and hiding mechanism.
5403\item[Effect on original feature:] change to semantics of well-defined feature.
5404\item[Difficulty of converting:] Semantic transformation.
5405\item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version.
5406\end{description}
5407
5408\item
5409\begin{description}
5410\item[Change:] In C++, the name of a nested class is local to its enclosing class.
5411\item[Rationale:] C++ classes have member functions which require that classes establish scopes.
5412\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:
5413\begin{cfa}
5414struct Y;                                               �\C{// struct Y and struct X are at the same scope}
5415struct X {
5416        struct Y { /* ... */ } y;
5417};
5418\end{cfa}
5419All 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.
5420Note: this is a consequence of the difference in scope rules, which is documented in 3.3.
5421\item[How widely used:] Seldom.
5422\end{description}
5423
5424\item
5425\begin{description}
5426\item[Change:] comma expression is disallowed as subscript
5427\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.
5428\item[Effect on original feature:] change to semantics of well-defined feature.
5429\item[Difficulty of converting:] semantic transformation of �x[i,j]� to �x[(i,j)]�
5430\item[How widely used:] seldom.
5431\end{description}
5432\end{enumerate}
5433
5434
5435\section{Standard Headers}
5436\label{s:StandardHeaders}
5437
5438\Celeven prescribes the following standard header-files~\cite[\S~7.1.2]{C11} and \CFA adds to this list:
5439\begin{quote2}
5440\lstset{deletekeywords={float}}
5441\begin{tabular}{@{}llll|l@{}}
5442\multicolumn{4}{c|}{C11} & \multicolumn{1}{c}{\CFA}             \\
5443\hline
5444\begin{tabular}{@{}l@{}}
5445\Indexc{assert.h}               \\
5446\Indexc{complex.h}              \\
5447\Indexc{ctype.h}                \\
5448\Indexc{errno.h}                \\
5449\Indexc{fenv.h}                 \\
5450\Indexc{float.h}                \\
5451\Indexc{inttypes.h}             \\
5452\Indexc{iso646.h}               \\
5453\end{tabular}
5454&
5455\begin{tabular}{@{}l@{}}
5456\Indexc{limits.h}               \\
5457\Indexc{locale.h}               \\
5458\Indexc{math.h}                 \\
5459\Indexc{setjmp.h}               \\
5460\Indexc{signal.h}               \\
5461\Indexc{stdalign.h}             \\
5462\Indexc{stdarg.h}               \\
5463\Indexc{stdatomic.h}    \\
5464\end{tabular}
5465&
5466\begin{tabular}{@{}l@{}}
5467\Indexc{stdbool.h}              \\
5468\Indexc{stddef.h}               \\
5469\Indexc{stdint.h}               \\
5470\Indexc{stdio.h}                \\
5471\Indexc{stdlib.h}               \\
5472\Indexc{stdnoreturn.h}  \\
5473\Indexc{string.h}               \\
5474\Indexc{tgmath.h}               \\
5475\end{tabular}
5476&
5477\begin{tabular}{@{}l@{}}
5478\Indexc{threads.h}              \\
5479\Indexc{time.h}                 \\
5480\Indexc{uchar.h}                \\
5481\Indexc{wchar.h}                \\
5482\Indexc{wctype.h}               \\
5483                                                \\
5484                                                \\
5485                                                \\
5486\end{tabular}
5487&
5488\begin{tabular}{@{}l@{}}
5489\Indexc{unistd.h}               \\
5490\Indexc{gmp.h}                  \\
5491                                                \\
5492                                                \\
5493                                                \\
5494                                                \\
5495                                                \\
5496                                                \\
5497\end{tabular}
5498\end{tabular}
5499\end{quote2}
5500For the prescribed head-files, \CFA uses header interposition to wraps these includes in an �extern "C"�;
5501hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}).
5502All other C header files must be explicitly wrapped in �extern "C"� to prevent name mangling.
5503For \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.
5504
5505
5506\section{Standard Library}
5507\label{s:StandardLibrary}
5508
5509The \CFA standard-library wraps explicitly-polymorphic C routines into implicitly-polymorphic versions.
5510
5511
5512\subsection{Storage Management}
5513
5514The 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.
5515
5516Storage management provides the following capabilities:
5517\begin{description}
5518\item[fill]
5519after allocation the storage is filled with a specified character.
5520\item[resize]
5521an existing allocation is decreased or increased in size.
5522In 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.
5523For an increase in storage size, new storage after the copied data may be filled.
5524\item[alignment]
5525an allocation starts on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes.
5526\item[array]
5527the allocation size is scaled to the specified number of array elements.
5528An array may be filled, resized, or aligned.
5529\end{description}
5530The table shows allocation routines supporting different combinations of storage-management capabilities:
5531\begin{center}
5532\begin{tabular}{@{}lr|l|l|l|l@{}}
5533                &                                       & \multicolumn{1}{c|}{fill}     & resize        & alignment     & array \\
5534\hline
5535C               & �malloc�                      & no                    & no            & no            & no    \\
5536                & �calloc�                      & yes (0 only)  & no            & no            & yes   \\
5537                & �realloc�                     & no/copy               & yes           & no            & no    \\
5538                & �memalign�            & no                    & no            & yes           & no    \\
5539                & �posix_memalign�      & no                    & no            & yes           & no    \\
5540C11             & �aligned_alloc�       & no                    & no            & yes           & no    \\
5541\CFA    & �alloc�                       & no/copy/yes   & no/yes        & no            & yes   \\
5542                & �align_alloc�         & no/yes                & no            & yes           & yes   \\
5543\end{tabular}
5544\end{center}
5545It 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.
5546
5547\leavevmode
5548\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5549// C unsafe allocation
5550extern "C" {
5551void * mallac( size_t size );�\indexc{memset}
5552void * calloc( size_t dim, size_t size );�\indexc{calloc}
5553void * realloc( void * ptr, size_t size );�\indexc{realloc}
5554void * memalign( size_t align, size_t size );�\indexc{memalign}
5555int posix_memalign( void ** ptr, size_t align, size_t size );�\indexc{posix_memalign}
5556}
5557
5558// �\CFA� safe equivalents, i.e., implicit size specification
5559forall( dtype T | sized(T) ) T * malloc( void );
5560forall( dtype T | sized(T) ) T * calloc( size_t dim );
5561forall( dtype T | sized(T) ) T * realloc( T * ptr, size_t size );
5562forall( dtype T | sized(T) ) T * memalign( size_t align );
5563forall( dtype T | sized(T) ) T * aligned_alloc( size_t align );
5564forall( dtype T | sized(T) ) int posix_memalign( T ** ptr, size_t align );
5565
5566// �\CFA� safe general allocation, fill, resize, array
5567forall( dtype T | sized(T) ) T * alloc( void );�\indexc{alloc}
5568forall( dtype T | sized(T) ) T * alloc( char fill );
5569forall( dtype T | sized(T) ) T * alloc( size_t dim );
5570forall( dtype T | sized(T) ) T * alloc( size_t dim, char fill );
5571forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim );
5572forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim, char fill );
5573
5574// �\CFA� safe general allocation, align, fill, array
5575forall( dtype T | sized(T) ) T * align_alloc( size_t align );
5576forall( dtype T | sized(T) ) T * align_alloc( size_t align, char fill );
5577forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim );
5578forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim, char fill );
5579
5580// C unsafe initialization/copy
5581extern "C" {
5582void * memset( void * dest, int c, size_t size );
5583void * memcpy( void * dest, const void * src, size_t size );
5584}
5585
5586// �\CFA� safe initialization/copy, i.e., implicit size specification
5587forall( dtype T | sized(T) ) T * memset( T * dest, char c );�\indexc{memset}
5588forall( dtype T | sized(T) ) T * memcpy( T * dest, const T * src );�\indexc{memcpy}
5589
5590// �\CFA� safe initialization/copy array
5591forall( dtype T | sized(T) ) T * memset( T dest[], size_t dim, char c );
5592forall( dtype T | sized(T) ) T * memcpy( T dest[], const T src[], size_t dim );
5593
5594// �\CFA� allocation/deallocation and constructor/destructor
5595forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * new( Params p );�\indexc{new}
5596forall( dtype T | { void ^?{}( T * ); } ) void delete( T * ptr );�\indexc{delete}
5597forall( dtype T, ttype Params | { void ^?{}( T * ); void delete( Params ); } )
5598  void delete( T * ptr, Params rest );
5599
5600// �\CFA� allocation/deallocation and constructor/destructor, array
5601forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * anew( size_t dim, Params p );�\indexc{anew}
5602forall( dtype T | sized(T) | { void ^?{}( T * ); } ) void adelete( size_t dim, T arr[] );�\indexc{adelete}
5603forall( dtype T | sized(T) | { void ^?{}( T * ); }, ttype Params | { void adelete( Params ); } )
5604  void adelete( size_t dim, T arr[], Params rest );
5605\end{cfa}
5606
5607
5608\subsection{Conversion}
5609
5610\leavevmode
5611\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5612int ato( const char * ptr );�\indexc{ato}
5613unsigned int ato( const char * ptr );
5614long int ato( const char * ptr );
5615unsigned long int ato( const char * ptr );
5616long long int ato( const char * ptr );
5617unsigned long long int ato( const char * ptr );
5618float ato( const char * ptr );
5619double ato( const char * ptr );
5620long double ato( const char * ptr );
5621float _Complex ato( const char * ptr );
5622double _Complex ato( const char * ptr );
5623long double _Complex ato( const char * ptr );
5624
5625int strto( const char * sptr, char ** eptr, int base );
5626unsigned int strto( const char * sptr, char ** eptr, int base );
5627long int strto( const char * sptr, char ** eptr, int base );
5628unsigned long int strto( const char * sptr, char ** eptr, int base );
5629long long int strto( const char * sptr, char ** eptr, int base );
5630unsigned long long int strto( const char * sptr, char ** eptr, int base );
5631float strto( const char * sptr, char ** eptr );
5632double strto( const char * sptr, char ** eptr );
5633long double strto( const char * sptr, char ** eptr );
5634float _Complex strto( const char * sptr, char ** eptr );
5635double _Complex strto( const char * sptr, char ** eptr );
5636long double _Complex strto( const char * sptr, char ** eptr );
5637\end{cfa}
5638
5639
5640\subsection{Search / Sort}
5641
5642\leavevmode
5643\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5644forall( otype T | { int ?<?( T, T ); } )        �\C{// location}
5645T * bsearch( T key, const T * arr, size_t dim );�\indexc{bsearch}
5646
5647forall( otype T | { int ?<?( T, T ); } )        �\C{// position}
5648unsigned int bsearch( T key, const T * arr, size_t dim );
5649
5650forall( otype T | { int ?<?( T, T ); } )
5651void qsort( const T * arr, size_t dim );�\indexc{qsort}
5652\end{cfa}
5653
5654
5655\subsection{Absolute Value}
5656
5657\leavevmode
5658\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5659unsigned char abs( signed char );�\indexc{abs}
5660int abs( int );
5661unsigned long int abs( long int );
5662unsigned long long int abs( long long int );
5663float abs( float );
5664double abs( double );
5665long double abs( long double );
5666float abs( float _Complex );
5667double abs( double _Complex );
5668long double abs( long double _Complex );
5669forall( otype T | { void ?{}( T *, zero_t ); int ?<?( T, T ); T -?( T ); } )
5670T abs( T );
5671\end{cfa}
5672
5673
5674\subsection{Random Numbers}
5675
5676\leavevmode
5677\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5678void rand48seed( long int s );�\indexc{rand48seed}
5679char rand48();�\indexc{rand48}
5680int rand48();
5681unsigned int rand48();
5682long int rand48();
5683unsigned long int rand48();
5684float rand48();
5685double rand48();
5686float _Complex rand48();
5687double _Complex rand48();
5688long double _Complex rand48();
5689\end{cfa}
5690
5691
5692\subsection{Algorithms}
5693
5694\leavevmode
5695\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5696forall( otype T | { int ?<?( T, T ); } ) T min( T t1, T t2 );�\indexc{min}
5697forall( otype T | { int ?>?( T, T ); } ) T max( T t1, T t2 );�\indexc{max}
5698forall( otype T | { T min( T, T ); T max( T, T ); } ) T clamp( T value, T min_val, T max_val );�\indexc{clamp}
5699forall( otype T ) void swap( T * t1, T * t2 );�\indexc{swap}
5700\end{cfa}
5701
5702
5703\section{Math Library}
5704\label{s:Math Library}
5705
5706The \CFA math-library wraps explicitly-polymorphic C math-routines into implicitly-polymorphic versions.
5707
5708
5709\subsection{General}
5710
5711\leavevmode
5712\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5713float ?%?( float, float );�\indexc{fmod}�
5714float fmod( float, float );
5715double ?%?( double, double );
5716double fmod( double, double );
5717long double ?%?( long double, long double );
5718long double fmod( long double, long double );
5719
5720float remainder( float, float );�\indexc{remainder}
5721double remainder( double, double );
5722long double remainder( long double, long double );
5723
5724[ int, float ] remquo( float, float );�\indexc{remquo}
5725float remquo( float, float, int * );
5726[ int, double ] remquo( double, double );
5727double remquo( double, double, int * );
5728[ int, long double ] remquo( long double, long double );
5729long double remquo( long double, long double, int * );
5730
5731[ int, float ] div( float, float );                                             // alternative name for remquo
5732float div( float, float, int * );�\indexc{div}
5733[ int, double ] div( double, double );
5734double div( double, double, int * );
5735[ int, long double ] div( long double, long double );
5736long double div( long double, long double, int * );
5737
5738float fma( float, float, float );�\indexc{fma}
5739double fma( double, double, double );
5740long double fma( long double, long double, long double );
5741
5742float fdim( float, float );�\indexc{fdim}
5743double fdim( double, double );
5744long double fdim( long double, long double );
5745
5746float nan( const char * );�\indexc{nan}
5747double nan( const char * );
5748long double nan( const char * );
5749\end{cfa}
5750
5751
5752\subsection{Exponential}
5753
5754\leavevmode
5755\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5756float exp( float );�\indexc{exp}
5757double exp( double );
5758long double exp( long double );
5759float _Complex exp( float _Complex );
5760double _Complex exp( double _Complex );
5761long double _Complex exp( long double _Complex );
5762
5763float exp2( float );�\indexc{exp2}
5764double exp2( double );
5765long double exp2( long double );
5766float _Complex exp2( float _Complex );
5767double _Complex exp2( double _Complex );
5768long double _Complex exp2( long double _Complex );
5769
5770float expm1( float );�\indexc{expm1}
5771double expm1( double );
5772long double expm1( long double );
5773
5774float log( float );�\indexc{log}
5775double log( double );
5776long double log( long double );
5777float _Complex log( float _Complex );
5778double _Complex log( double _Complex );
5779long double _Complex log( long double _Complex );
5780
5781float log2( float );�\indexc{log2}
5782double log2( double );
5783long double log2( long double );
5784float _Complex log2( float _Complex );
5785double _Complex log2( double _Complex );
5786long double _Complex log2( long double _Complex );
5787
5788float log10( float );�\indexc{log10}
5789double log10( double );
5790long double log10( long double );
5791float _Complex log10( float _Complex );
5792double _Complex log10( double _Complex );
5793long double _Complex log10( long double _Complex );
5794
5795float log1p( float );�\indexc{log1p}
5796double log1p( double );
5797long double log1p( long double );
5798
5799int ilogb( float );�\indexc{ilogb}
5800int ilogb( double );
5801int ilogb( long double );
5802
5803float logb( float );�\indexc{logb}
5804double logb( double );
5805long double logb( long double );
5806\end{cfa}
5807
5808
5809\subsection{Power}
5810
5811\leavevmode
5812\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5813float sqrt( float );�\indexc{sqrt}
5814double sqrt( double );
5815long double sqrt( long double );
5816float _Complex sqrt( float _Complex );
5817double _Complex sqrt( double _Complex );
5818long double _Complex sqrt( long double _Complex );
5819
5820float cbrt( float );�\indexc{cbrt}
5821double cbrt( double );
5822long double cbrt( long double );
5823
5824float hypot( float, float );�\indexc{hypot}
5825double hypot( double, double );
5826long double hypot( long double, long double );
5827
5828float pow( float, float );�\indexc{pow}
5829double pow( double, double );
5830long double pow( long double, long double );
5831float _Complex pow( float _Complex, float _Complex );
5832double _Complex pow( double _Complex, double _Complex );
5833long double _Complex pow( long double _Complex, long double _Complex );
5834\end{cfa}
5835
5836
5837\subsection{Trigonometric}
5838
5839\leavevmode
5840\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5841float sin( float );�\indexc{sin}
5842double sin( double );
5843long double sin( long double );
5844float _Complex sin( float _Complex );
5845double _Complex sin( double _Complex );
5846long double _Complex sin( long double _Complex );
5847
5848float cos( float );�\indexc{cos}
5849double cos( double );
5850long double cos( long double );
5851float _Complex cos( float _Complex );
5852double _Complex cos( double _Complex );
5853long double _Complex cos( long double _Complex );
5854
5855float tan( float );�\indexc{tan}
5856double tan( double );
5857long double tan( long double );
5858float _Complex tan( float _Complex );
5859double _Complex tan( double _Complex );
5860long double _Complex tan( long double _Complex );
5861
5862float asin( float );�\indexc{asin}
5863double asin( double );
5864long double asin( long double );
5865float _Complex asin( float _Complex );
5866double _Complex asin( double _Complex );
5867long double _Complex asin( long double _Complex );
5868
5869float acos( float );�\indexc{acos}
5870double acos( double );
5871long double acos( long double );
5872float _Complex acos( float _Complex );
5873double _Complex acos( double _Complex );
5874long double _Complex acos( long double _Complex );
5875
5876float atan( float );�\indexc{atan}
5877double atan( double );
5878long double atan( long double );
5879float _Complex atan( float _Complex );
5880double _Complex atan( double _Complex );
5881long double _Complex atan( long double _Complex );
5882
5883float atan2( float, float );�\indexc{atan2}
5884double atan2( double, double );
5885long double atan2( long double, long double );
5886
5887float atan( float, float );                                                             // alternative name for atan2
5888double atan( double, double );�\indexc{atan}
5889long double atan( long double, long double );
5890\end{cfa}
5891
5892
5893\subsection{Hyperbolic}
5894
5895\leavevmode
5896\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5897float sinh( float );�\indexc{sinh}
5898double sinh( double );
5899long double sinh( long double );
5900float _Complex sinh( float _Complex );
5901double _Complex sinh( double _Complex );
5902long double _Complex sinh( long double _Complex );
5903
5904float cosh( float );�\indexc{cosh}
5905double cosh( double );
5906long double cosh( long double );
5907float _Complex cosh( float _Complex );
5908double _Complex cosh( double _Complex );
5909long double _Complex cosh( long double _Complex );
5910
5911float tanh( float );�\indexc{tanh}
5912double tanh( double );
5913long double tanh( long double );
5914float _Complex tanh( float _Complex );
5915double _Complex tanh( double _Complex );
5916long double _Complex tanh( long double _Complex );
5917
5918float asinh( float );�\indexc{asinh}
5919double asinh( double );
5920long double asinh( long double );
5921float _Complex asinh( float _Complex );
5922double _Complex asinh( double _Complex );
5923long double _Complex asinh( long double _Complex );
5924
5925float acosh( float );�\indexc{acosh}
5926double acosh( double );
5927long double acosh( long double );
5928float _Complex acosh( float _Complex );
5929double _Complex acosh( double _Complex );
5930long double _Complex acosh( long double _Complex );
5931
5932float atanh( float );�\indexc{atanh}
5933double atanh( double );
5934long double atanh( long double );
5935float _Complex atanh( float _Complex );
5936double _Complex atanh( double _Complex );
5937long double _Complex atanh( long double _Complex );
5938\end{cfa}
5939
5940
5941\subsection{Error / Gamma}
5942
5943\leavevmode
5944\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5945float erf( float );�\indexc{erf}
5946double erf( double );
5947long double erf( long double );
5948float _Complex erf( float _Complex );
5949double _Complex erf( double _Complex );
5950long double _Complex erf( long double _Complex );
5951
5952float erfc( float );�\indexc{erfc}
5953double erfc( double );
5954long double erfc( long double );
5955float _Complex erfc( float _Complex );
5956double _Complex erfc( double _Complex );
5957long double _Complex erfc( long double _Complex );
5958
5959float lgamma( float );�\indexc{lgamma}
5960double lgamma( double );
5961long double lgamma( long double );
5962float lgamma( float, int * );
5963double lgamma( double, int * );
5964long double lgamma( long double, int * );
5965
5966float tgamma( float );�\indexc{tgamma}
5967double tgamma( double );
5968long double tgamma( long double );
5969\end{cfa}
5970
5971
5972\subsection{Nearest Integer}
5973
5974\leavevmode
5975\begin{cfa}[aboveskip=0pt,belowskip=0pt]
5976float floor( float );�\indexc{floor}
5977double floor( double );
5978long double floor( long double );
5979
5980float ceil( float );�\indexc{ceil}
5981double ceil( double );
5982long double ceil( long double );
5983
5984float trunc( float );�\indexc{trunc}
5985double trunc( double );
5986long double trunc( long double );
5987
5988float rint( float );�\indexc{rint}
5989long double rint( long double );
5990long int rint( float );
5991long int rint( double );
5992long int rint( long double );
5993long long int rint( float );
5994long long int rint( double );
5995long long int rint( long double );
5996
5997long int lrint( float );�\indexc{lrint}
5998long int lrint( double );
5999long int lrint( long double );
6000long long int llrint( float );
6001long long int llrint( double );
6002long long int llrint( long double );
6003
6004float nearbyint( float );�\indexc{nearbyint}
6005double nearbyint( double );
6006long double nearbyint( long double );
6007
6008float round( float );�\indexc{round}
6009long double round( long double );
6010long int round( float );
6011long int round( double );
6012long int round( long double );
6013long long int round( float );
6014long long int round( double );
6015long long int round( long double );
6016
6017long int lround( float );�\indexc{lround}
6018long int lround( double );
6019long int lround( long double );
6020long long int llround( float );
6021long long int llround( double );
6022long long int llround( long double );
6023\end{cfa}
6024
6025
6026\subsection{Manipulation}
6027
6028\leavevmode
6029\begin{cfa}[aboveskip=0pt,belowskip=0pt]
6030float copysign( float, float );�\indexc{copysign}
6031double copysign( double, double );
6032long double copysign( long double, long double );
6033
6034float frexp( float, int * );�\indexc{frexp}
6035double frexp( double, int * );
6036long double frexp( long double, int * );
6037
6038float ldexp( float, int );�\indexc{ldexp}
6039double ldexp( double, int );
6040long double ldexp( long double, int );
6041
6042[ float, float ] modf( float );�\indexc{modf}
6043float modf( float, float * );
6044[ double, double ] modf( double );
6045double modf( double, double * );
6046[ long double, long double ] modf( long double );
6047long double modf( long double, long double * );
6048
6049float nextafter( float, float );�\indexc{nextafter}
6050double nextafter( double, double );
6051long double nextafter( long double, long double );
6052
6053float nexttoward( float, long double );�\indexc{nexttoward}
6054double nexttoward( double, long double );
6055long double nexttoward( long double, long double );
6056
6057float scalbn( float, int );�\indexc{scalbn}
6058double scalbn( double, int );
6059long double scalbn( long double, int );
6060
6061float scalbln( float, long int );�\indexc{scalbln}
6062double scalbln( double, long int );
6063long double scalbln( long double, long int );
6064\end{cfa}
6065
6066
6067\section{Multi-precision Integers}
6068\label{s:MultiPrecisionIntegers}
6069
6070\CFA has an interface to the GMP \Index{multi-precision} signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP.
6071The \CFA interface wraps GMP routines into operator routines to make programming with multi-precision integers identical to using fixed-sized integers.
6072The \CFA type name for multi-precision signed-integers is \Indexc{Int} and the header file is \Indexc{gmp}.
6073
6074\begin{cfa}
6075void ?{}( Int * this );                                 �\C{// constructor}
6076void ?{}( Int * this, Int init );
6077void ?{}( Int * this, zero_t );
6078void ?{}( Int * this, one_t );
6079void ?{}( Int * this, signed long int init );
6080void ?{}( Int * this, unsigned long int init );
6081void ?{}( Int * this, const char * val );
6082void ^?{}( Int * this );
6083
6084Int ?=?( Int * lhs, Int rhs );                  �\C{// assignment}
6085Int ?=?( Int * lhs, long int rhs );
6086Int ?=?( Int * lhs, unsigned long int rhs );
6087Int ?=?( Int * lhs, const char * rhs );
6088
6089char ?=?( char * lhs, Int rhs );
6090short int ?=?( short int * lhs, Int rhs );
6091int ?=?( int * lhs, Int rhs );
6092long int ?=?( long int * lhs, Int rhs );
6093unsigned char ?=?( unsigned char * lhs, Int rhs );
6094unsigned short int ?=?( unsigned short int * lhs, Int rhs );
6095unsigned int ?=?( unsigned int * lhs, Int rhs );
6096unsigned long int ?=?( unsigned long int * lhs, Int rhs );
6097
6098long int narrow( Int val );
6099unsigned long int narrow( Int val );
6100
6101int ?==?( Int oper1, Int oper2 );               �\C{// comparison}
6102int ?==?( Int oper1, long int oper2 );
6103int ?==?( long int oper2, Int oper1 );
6104int ?==?( Int oper1, unsigned long int oper2 );
6105int ?==?( unsigned long int oper2, Int oper1 );
6106
6107int ?!=?( Int oper1, Int oper2 );
6108int ?!=?( Int oper1, long int oper2 );
6109int ?!=?( long int oper1, Int oper2 );
6110int ?!=?( Int oper1, unsigned long int oper2 );
6111int ?!=?( unsigned long int oper1, Int oper2 );
6112
6113int ?<?( Int oper1, Int oper2 );
6114int ?<?( Int oper1, long int oper2 );
6115int ?<?( long int oper2, Int oper1 );
6116int ?<?( Int oper1, unsigned long int oper2 );
6117int ?<?( unsigned long int oper2, Int oper1 );
6118
6119int ?<=?( Int oper1, Int oper2 );
6120int ?<=?( Int oper1, long int oper2 );
6121int ?<=?( long int oper2, Int oper1 );
6122int ?<=?( Int oper1, unsigned long int oper2 );
6123int ?<=?( unsigned long int oper2, Int oper1 );
6124
6125int ?>?( Int oper1, Int oper2 );
6126int ?>?( Int oper1, long int oper2 );
6127int ?>?( long int oper1, Int oper2 );
6128int ?>?( Int oper1, unsigned long int oper2 );
6129int ?>?( unsigned long int oper1, Int oper2 );
6130
6131int ?>=?( Int oper1, Int oper2 );
6132int ?>=?( Int oper1, long int oper2 );
6133int ?>=?( long int oper1, Int oper2 );
6134int ?>=?( Int oper1, unsigned long int oper2 );
6135int ?>=?( unsigned long int oper1, Int oper2 );
6136
6137Int +?( Int oper );                                             �\C{// arithmetic}
6138Int -?( Int oper );
6139Int ~?( Int oper );
6140
6141Int ?&?( Int oper1, Int oper2 );
6142Int ?&?( Int oper1, long int oper2 );
6143Int ?&?( long int oper1, Int oper2 );
6144Int ?&?( Int oper1, unsigned long int oper2 );
6145Int ?&?( unsigned long int oper1, Int oper2 );
6146Int ?&=?( Int * lhs, Int rhs );
6147
6148Int ?|?( Int oper1, Int oper2 );
6149Int ?|?( Int oper1, long int oper2 );
6150Int ?|?( long int oper1, Int oper2 );
6151Int ?|?( Int oper1, unsigned long int oper2 );
6152Int ?|?( unsigned long int oper1, Int oper2 );
6153Int ?|=?( Int * lhs, Int rhs );
6154
6155Int ?^?( Int oper1, Int oper2 );
6156Int ?^?( Int oper1, long int oper2 );
6157Int ?^?( long int oper1, Int oper2 );
6158Int ?^?( Int oper1, unsigned long int oper2 );
6159Int ?^?( unsigned long int oper1, Int oper2 );
6160Int ?^=?( Int * lhs, Int rhs );
6161
6162Int ?+?( Int addend1, Int addend2 );
6163Int ?+?( Int addend1, long int addend2 );
6164Int ?+?( long int addend2, Int addend1 );
6165Int ?+?( Int addend1, unsigned long int addend2 );
6166Int ?+?( unsigned long int addend2, Int addend1 );
6167Int ?+=?( Int * lhs, Int rhs );
6168Int ?+=?( Int * lhs, long int rhs );
6169Int ?+=?( Int * lhs, unsigned long int rhs );
6170Int ++?( Int * lhs );
6171Int ?++( Int * lhs );
6172
6173Int ?-?( Int minuend, Int subtrahend );
6174Int ?-?( Int minuend, long int subtrahend );
6175Int ?-?( long int minuend, Int subtrahend );
6176Int ?-?( Int minuend, unsigned long int subtrahend );
6177Int ?-?( unsigned long int minuend, Int subtrahend );
6178Int ?-=?( Int * lhs, Int rhs );
6179Int ?-=?( Int * lhs, long int rhs );
6180Int ?-=?( Int * lhs, unsigned long int rhs );
6181Int --?( Int * lhs );
6182Int ?--( Int * lhs );
6183
6184Int ?*?( Int multiplicator, Int multiplicand );
6185Int ?*?( Int multiplicator, long int multiplicand );
6186Int ?*?( long int multiplicand, Int multiplicator );
6187Int ?*?( Int multiplicator, unsigned long int multiplicand );
6188Int ?*?( unsigned long int multiplicand, Int multiplicator );
6189Int ?*=?( Int * lhs, Int rhs );
6190Int ?*=?( Int * lhs, long int rhs );
6191Int ?*=?( Int * lhs, unsigned long int rhs );
6192
6193Int ?/?( Int dividend, Int divisor );
6194Int ?/?( Int dividend, unsigned long int divisor );
6195Int ?/?( unsigned long int dividend, Int divisor );
6196Int ?/?( Int dividend, long int divisor );
6197Int ?/?( long int dividend, Int divisor );
6198Int ?/=?( Int * lhs, Int rhs );
6199Int ?/=?( Int * lhs, long int rhs );
6200Int ?/=?( Int * lhs, unsigned long int rhs );
6201
6202[ Int, Int ] div( Int dividend, Int divisor );
6203[ Int, Int ] div( Int dividend, unsigned long int divisor );
6204
6205Int ?%?( Int dividend, Int divisor );
6206Int ?%?( Int dividend, unsigned long int divisor );
6207Int ?%?( unsigned long int dividend, Int divisor );
6208Int ?%?( Int dividend, long int divisor );
6209Int ?%?( long int dividend, Int divisor );
6210Int ?%=?( Int * lhs, Int rhs );
6211Int ?%=?( Int * lhs, long int rhs );
6212Int ?%=?( Int * lhs, unsigned long int rhs );
6213
6214Int ?<<?( Int shiften, mp_bitcnt_t shift );
6215Int ?<<=?( Int * lhs, mp_bitcnt_t shift );
6216Int ?>>?( Int shiften, mp_bitcnt_t shift );
6217Int ?>>=?( Int * lhs, mp_bitcnt_t shift );
6218
6219Int abs( Int oper );                                    �\C{// number functions}
6220Int fact( unsigned long int N );
6221Int gcd( Int oper1, Int oper2 );
6222Int pow( Int base, unsigned long int exponent );
6223Int pow( unsigned long int base, unsigned long int exponent );
6224void srandom( gmp_randstate_t state );
6225Int random( gmp_randstate_t state, mp_bitcnt_t n );
6226Int random( gmp_randstate_t state, Int n );
6227Int random( gmp_randstate_t state, mp_size_t max_size );
6228int sgn( Int oper );
6229Int sqrt( Int oper );
6230
6231forall( dtype istype | istream( istype ) ) istype * ?|?( istype * is, Int * mp );  �\C{// I/O}
6232forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype * os, Int mp );
6233\end{cfa}
6234
6235The following factorial programs contrast using GMP with the \CFA and C interfaces, where the output from these programs appears in \VRef[Figure]{f:MultiPrecisionFactorials}.
6236(Compile with flag \Indexc{-lgmp} to link with the GMP library.)
6237\begin{quote2}
6238\begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}}
6239\multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}}    & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}}      \\
6240\hline
6241\begin{cfa}
6242#include <gmp>�\indexc{gmp}
6243int main( void ) {
6244        sout | "Factorial Numbers" | endl;
6245        Int fact = 1;
6246
6247        sout | 0 | fact | endl;
6248        for ( unsigned int i = 1; i <= 40; i += 1 ) {
6249                fact *= i;
6250                sout | i | fact | endl;
6251        }
6252}
6253\end{cfa}
6254&
6255\begin{cfa}
6256#include <gmp.h>�\indexc{gmp.h}
6257int main( void ) {
6258        �gmp_printf�( "Factorial Numbers\n" );
6259        �mpz_t� fact;
6260        �mpz_init_set_ui�( fact, 1 );
6261        �gmp_printf�( "%d %Zd\n", 0, fact );
6262        for ( unsigned int i = 1; i <= 40; i += 1 ) {
6263                �mpz_mul_ui�( fact, fact, i );
6264                �gmp_printf�( "%d %Zd\n", i, fact );
6265        }
6266}
6267\end{cfa}
6268\end{tabular}
6269\end{quote2}
6270
6271\begin{figure}
6272\begin{cfa}
6273Factorial Numbers
62740 1
62751 1
62762 2
62773 6
62784 24
62795 120
62806 720
62817 5040
62828 40320
62839 362880
628410 3628800
628511 39916800
628612 479001600
628713 6227020800
628814 87178291200
628915 1307674368000
629016 20922789888000
629117 355687428096000
629218 6402373705728000
629319 121645100408832000
629420 2432902008176640000
629521 51090942171709440000
629622 1124000727777607680000
629723 25852016738884976640000
629824 620448401733239439360000
629925 15511210043330985984000000
630026 403291461126605635584000000
630127 10888869450418352160768000000
630228 304888344611713860501504000000
630329 8841761993739701954543616000000
630430 265252859812191058636308480000000
630531 8222838654177922817725562880000000
630632 263130836933693530167218012160000000
630733 8683317618811886495518194401280000000
630834 295232799039604140847618609643520000000
630935 10333147966386144929666651337523200000000
631036 371993326789901217467999448150835200000000
631137 13763753091226345046315979581580902400000000
631238 523022617466601111760007224100074291200000000
631339 20397882081197443358640281739902897356800000000
631440 815915283247897734345611269596115894272000000000
6315\end{cfa}
6316\caption{Multi-precision Factorials}
6317\label{f:MultiPrecisionFactorials}
6318\end{figure}
6319
6320
6321\section{Rational Numbers}
6322\label{s:RationalNumbers}
6323
6324Rational numbers are numbers written as a ratio, \ie as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers.
6325When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible.
6326
6327\begin{cfa}[belowskip=0pt]
6328// implementation
6329struct Rational {\indexc{Rational}
6330        long int numerator, denominator;                                        // invariant: denominator > 0
6331}; // Rational
6332
6333Rational rational();                                    �\C{// constructors}
6334Rational rational( long int n );
6335Rational rational( long int n, long int d );
6336void ?{}( Rational * r, zero_t );
6337void ?{}( Rational * r, one_t );
6338
6339long int numerator( Rational r );               �\C{// numerator/denominator getter/setter}
6340long int numerator( Rational r, long int n );
6341long int denominator( Rational r );
6342long int denominator( Rational r, long int d );
6343
6344int ?==?( Rational l, Rational r );             �\C{// comparison}
6345int ?!=?( Rational l, Rational r );
6346int ?<?( Rational l, Rational r );
6347int ?<=?( Rational l, Rational r );
6348int ?>?( Rational l, Rational r );
6349int ?>=?( Rational l, Rational r );
6350
6351Rational -?( Rational r );                              �\C{// arithmetic}
6352Rational ?+?( Rational l, Rational r );
6353Rational ?-?( Rational l, Rational r );
6354Rational ?*?( Rational l, Rational r );
6355Rational ?/?( Rational l, Rational r );
6356
6357double widen( Rational r );                             �\C{// conversion}
6358Rational narrow( double f, long int md );
6359
6360forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * ); // I/O
6361forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational );
6362\end{cfa}
6363
6364
6365\bibliographystyle{plain}
6366\bibliography{cfa}
6367
6368
6369\addcontentsline{toc}{section}{\indexname} % add index name to table of contents
6370\begin{theindex}
6371Italic page numbers give the location of the main entry for the referenced term.
6372Plain page numbers denote uses of the indexed term.
6373Entries for grammar non-terminals are italicized.
6374A typewriter font is used for grammar terminals and program identifiers.
6375\indexspace
6376\input{user.ind}
6377\end{theindex}
6378
6379
6380\end{document}
6381
6382% Local Variables: %
6383% tab-width: 4 %
6384% fill-column: 100 %
6385% compile-command: "make" %
6386% End: %
Note: See TracBrowser for help on using the repository browser.