source: doc/user/user.tex @ e9a3c69d

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

allow lstinline in section headings with PDF TOC

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