source: doc/user/user.tex @ 917ab04

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 917ab04 was 917ab04, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

rewrite section syntax ambiguites

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