source: doc/user/user.tex @ 27caf8d

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

updates to pointers/references section

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