source: doc/user/user.tex @ d6fb3c7

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

Merge branch 'master' of plg2:software/cfa/cfa-cc

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