source: doc/user/user.tex @ 83e680d

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

updates to exponential operator

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