source: doc/user/user.tex @ e9bb0e5

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

update beginning material, add short discussion on "with" clause/statement

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