source: doc/user/user.tex @ 8712514

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationresolv-newwith_gc
Last change on this file since 8712514 was 58ed882, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

many updates

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