source: doc/user/user.tex @ 0642216

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

rewrite Pointer/Reference? section

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