source: doc/user/user.tex @ 421a287

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

update allocation documentation

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