source: doc/user/user.tex @ 038726d

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglergc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newstringwith_gc
Last change on this file since 038726d was 6c91065, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

start user manual

  • Property mode set to 100644
File size: 162.7 KB
Line 
1% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
2
3\documentclass[openright,twoside]{article}
4%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5
6% Latex packages used in the document.
7
8\usepackage{fullpage,times}
9\usepackage{xspace}
10\usepackage{varioref}
11\usepackage{listings}
12\usepackage{footmisc}
13\usepackage{comment}
14\usepackage{latexsym}                                   % \Box
15\usepackage{mathptmx}                                   % better math font with "times"
16\usepackage[pagewise]{lineno}
17\renewcommand{\linenumberfont}{\scriptsize\sffamily}
18\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
19\usepackage{breakurl}
20\renewcommand{\UrlFont}{\small\sf}
21
22%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
23
24% Names used in the document.
25
26\newcommand{\CFA}{C$\forall$\xspace}    % set language symbolic name
27\newcommand{\CFL}{Cforall\xspace}               % set language text name
28\newcommand{\CC}{C\kern-.1em\hbox{+\kern-.25em+}\xspace} % CC symbolic name
29\def\c11{ISO/IEC C} % C11 name (cannot have numbers in latex command name)
30\newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace}
31
32%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
33
34% Bespoke macros used in the document.
35
36\makeatletter
37% allow escape sequence in lstinline
38%\usepackage{etoolbox}
39%\patchcmd{\lsthk@TextStyle}{\let\lst@DefEsc\@empty}{}{}{\errmessage{failed to patch}}
40
41\renewcommand\small{%
42   \@setfontsize\small{8.5}{11}%
43   \abovedisplayskip 8.5pt \@plus 3pt \@minus 4pt
44   \abovedisplayshortskip \z@ \@plus 2pt
45   \belowdisplayshortskip 4pt \@plus 2pt \@minus 2pt
46   \def\@listi{\leftmargin\leftmargini
47               \topsep 4pt \@plus 2pt \@minus 2pt
48               \parsep 2pt \@pluspt \@minuspt
49               \itemsep \parsep}%
50   \belowdisplayskip \abovedisplayskip
51}
52\usepackage{relsize}            % must be after change to small
53
54\renewcommand{\labelitemi}{{\raisebox{0.25ex}{\footnotesize$\bullet$}}}
55\renewenvironment{itemize}{\begin{list}{\labelitemi}{\topsep=5pt\itemsep=5pt\parsep=0pt}}{\end{list}}
56
57%  Reduce size of section titles
58\renewcommand\section{\@startsection{section}{1}{\z@}{-3.0ex \@plus -1ex \@minus -.2ex}{1.0ex \@plus .2ex}{\normalfont\large\bfseries}}
59\renewcommand\subsection{\@startsection{subsection}{2}{\z@}{-2.5ex \@plus -1ex \@minus -.2ex}{1.0ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
60\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex \@plus -1ex \@minus -.2ex}{1.0ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
61\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}{-2.0ex \@plus -1ex \@minus -.2ex}{-1em}{\normalfont\normalsize\bfseries}}
62
63% index macros
64\newcommand{\italic}[1]{\emph{\hyperpage{#1}}}
65\newcommand{\definition}[1]{\textbf{\hyperpage{#1}}}
66\newcommand{\see}[1]{\emph{see} #1}
67
68% Define some commands that produce formatted index entries suitable for cross-references.
69% ``\spec'' produces entries for specifications of entities.  ``\impl'' produces entries for their
70% implementations, and ``\use'' for their uses.
71
72%  \newcommand{\bold}[1]{{\bf #1}}
73%  \def\spec{\@bsphack\begingroup
74%             \def\protect##1{\string##1\space}\@sanitize
75%             \@wrxref{|bold}}
76\def\impl{\@bsphack\begingroup
77          \def\protect##1{\string##1\space}\@sanitize
78          \@wrxref{|definition}}
79\newcommand{\indexcode}[1]{{\lstinline$#1$}}
80\def\use{\@bsphack\begingroup
81         \def\protect##1{\string##1\space}\@sanitize
82         \@wrxref{|hyperpage}}
83\def\@wrxref#1#2{\let\thepage\relax
84    \xdef\@gtempa{\write\@indexfile{\string
85    \indexentry{#2@{\lstinline$#2$}#1}{\thepage}}}\endgroup\@gtempa
86    \if@nobreak \ifvmode\nobreak\fi\fi\@esphack}
87%\newcommand{\use}[1]{\index{#1@{\lstinline$#1$}}}
88%\newcommand{\impl}[1]{\index{\protect#1@{\lstinline$\protect#1$}|definition}}
89
90% inline text and lowercase index: \Index{inline and lowercase index text}
91% inline text and as-in index: \Index[as-is index text]{inline text}
92% inline text but index with different as-is text: \Index[index text]{inline text}
93\newcommand{\Index}{\@ifstar\@sIndex\@Index}
94\newcommand{\@Index}[2][\@empty]{\lowercase{\def\temp{#2}}#2\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
95\newcommand{\@sIndex}[2][\@empty]{#2\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
96
97\newcommand{\newtermFontInline}{\emph}
98\newcommand{\newterm}{\@ifstar\@snewterm\@newterm}
99\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
100\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
101\makeatother
102
103% blocks and titles
104\newenvironment{quote2}{%
105        \list{}{\lstset{resetmargins=true}\leftmargin=\parindent\rightmargin\leftmargin}%
106        \item\relax
107}{%
108        \endlist
109}% quote2
110\newenvironment{rationale}{%
111  \begin{quotation}\noindent$\Box$\enspace
112}{%
113  \hfill\enspace$\Box$\end{quotation}
114}%
115\newcommand{\define}[1]{\emph{#1\/}\index{#1}}
116\newcommand{\rewrite}{\(\Rightarrow\)}
117\newcommand{\rewriterules}{\paragraph{Rewrite Rules}~\par\noindent}
118\newcommand{\examples}{\paragraph{Examples}~\par\noindent}
119\newcommand{\semantics}{\paragraph{Semantics}~\par\noindent}
120\newcommand{\constraints}{\paragraph{Constraints}~\par\noindent}
121\newcommand{\predefined}{\paragraph{Predefined Identifiers}~\par\noindent}
122
123% BNF macros
124\def\syntax{\paragraph{Syntax}\trivlist\parindent=.5in\item[\hskip.5in]}
125\let\endsyntax=\endtrivlist
126\newcommand{\lhs}[1]{\par{\emph{#1:}}\index{#1@{\emph{#1}}|italic}}
127\newcommand{\rhs}{\hfil\break\hbox{\hskip1in}}
128\newcommand{\oldlhs}[1]{\emph{#1: \ldots}\index{#1@{\emph{#1}}|italic}}
129\newcommand{\nonterm}[1]{\emph{#1\/}\index{#1@{\emph{#1}}|italic}}
130\newcommand{\opt}{$_{opt}$\ }
131
132% adjust varioref package with default "section" and "page" titles, and optional title with faraway page numbers
133% \VRef{label} => Section 2.7, \VPageref{label} => page 17
134% \VRef[Figure]{label} => Figure 3.4, \VPageref{label} => page 17
135\renewcommand{\reftextfaceafter}{\unskip}
136\renewcommand{\reftextfacebefore}{\unskip}
137\renewcommand{\reftextafter}{\unskip}
138\renewcommand{\reftextbefore}{\unskip}
139\renewcommand{\reftextfaraway}[1]{\unskip, p.~\pageref{#1}}
140\renewcommand{\reftextpagerange}[2]{\unskip, pp.~\pageref{#1}--\pageref{#2}}
141\newcommand{\VRef}[2][Section]{\ifx#1\@empty\else{#1}\nobreakspace\fi\vref{#2}}
142\newcommand{\VPageref}[2][page]{\ifx#1\@empty\else{#1}\nobreakspace\fi\pageref{#2}}
143
144% Go programming language
145\lstdefinelanguage{Golang}%
146  {morekeywords=[1]{package,import,func,type,struct,return,defer,panic, recover,select,var,const,iota,},%
147   morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16, int32,int64,
148                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},%
149   morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false, delete,append,real,imag,complex,chan,},%
150   morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if, else,default,},%
151   morekeywords=[5]{Println,Printf,Error,},%
152   sensitive=true,%
153   morecomment=[l]{//},%
154   morecomment=[s]{/*}{*/},%
155   morestring=[b]',%
156   morestring=[b]",%
157   morestring=[s]{`}{`},%
158}
159
160% CFA based on ANSI C
161\lstdefinelanguage{CFA}[ANSI]{C}%
162{morekeywords={asm,_Alignas,_Alignof,_At,_Atomic,_Bool,catch,catchResume,choose,_Complex,trait,disable,dtype,enable,
163        fallthru,finally,forall,ftype,_Generic,_Imaginary,inline,lvalue,_Noreturn,otype,restrict,_Static_assert,
164        _Thread_local,throw,throwResume,try,},
165}%
166
167\lstset{
168language=CFA,
169columns=flexible,
170basicstyle=\sf\relsize{-1},
171tabsize=4,
172xleftmargin=\parindent,
173escapechar=@,
174mathescape=true,
175keepspaces=true,
176showstringspaces=false,
177showlines=true,
178}%
179
180\makeatletter
181% replace/adjust listings characters that look bad in sanserif
182\lst@CCPutMacro
183\lst@ProcessOther{"2D}{\lst@ttfamily{-{}}{{\ttfamily\upshape -}}} % replace minus
184\lst@ProcessOther{"3C}{\lst@ttfamily{<}{\texttt{<}}} % replace less than
185\lst@ProcessOther{"3E}{\lst@ttfamily{<}{\texttt{>}}} % replace greater than
186\lst@ProcessOther{"5E}{\raisebox{0.4ex}{$\scriptstyle\land\,$}} % replace circumflex
187\lst@ProcessLetter{"5F}{\lst@ttfamily{\char95}{{\makebox[1.2ex][c]{\rule{1ex}{0.1ex}}}}} % replace underscore
188\lst@ProcessOther{"7E}{\raisebox{0.3ex}{$\scriptstyle\sim\,$}} % replace tilde
189%\lst@ProcessOther{"7E}{\raisebox{-.4ex}[1ex][0pt]{\textasciitilde}} % lower tilde
190\@empty\z@\@empty
191\makeatother
192
193\setcounter{secnumdepth}{3}     % number subsubsections
194\setcounter{tocdepth}{3}                % subsubsections in table of contents
195\makeindex
196
197%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
198
199\begin{document}
200\pagestyle{headings}
201\linenumbers                                    % comment out to turn off line numbering
202
203\title{\Huge
204\vspace*{1in}
205\CFA (\CFL) User Manual                         \\
206Version 1.0                                                     \\
207\vspace*{0.25in}
208\huge``describe not prescribe''         \\
209\vspace*{1in}
210}% title
211\author{\huge
212Peter A. Buhr and ...                           \\
213}% author
214\date{
215DRAFT\\\today
216}% date
217
218\pagenumbering{roman}
219\pagestyle{plain}
220
221\maketitle
222
223\vspace*{\fill}
224\thispagestyle{empty}
225\noindent
226\copyright\,2016 \CFA Project \\ \\
227\noindent
228This work is licensed under the Creative Commons Attribution 4.0 International License.
229To view a copy of this license, visit {\small\url{http://creativecommons.org/licenses/by/4.0}}.
230\vspace*{1in}
231
232\clearpage
233\pdfbookmark[1]{Contents}{section}
234\tableofcontents
235
236\clearpage
237\pagenumbering{arabic}
238
239
240\section{Introduction}
241
242\CFA\footnote{Pronounced ``C-for-all'', and written \CFA, CFA, or \CFL.} is a modern general-purpose programming-language, designed an as evolutionary step forward from the C programming language.
243The syntax of the \CFA language builds from that of C, and should look immediately familiar to C programmers.
244% Any language feature that is not described here can be assumed to be using the standard C11 syntax.
245\CFA has added many modern programming-language features, which directly leads to increased safety and productivity, while maintaining interoperability with existing C programs, and maintaining C-like performance.
246Like C, \CFA is a statically typed, procedural language with a low-overhead runtime, meaning there is no global garbage-collection.
247The primary new features include parametric-polymorphism routines and types, exceptions, concurrency, and modules.
248
249One 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''.
250Programmers 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.
251A 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.
252There is no notion or requirement for rewriting a legacy C program in \CFA;
253instead, a programmer evolves an existing C program into \CFA by incrementally incorporating \CFA features.
254New programs can be written in \CFA using a combination of C and \CFA features.
255\CC had a similar goal 30 years ago, but has struggled over the intervening time to incorporate modern programming-language features because of early design choices.
256\CFA has 30 years of hindsight and a much cleaner starting point than \CC.
257
258Like \CC, there may be both an old and new ways to achieve the same effect.
259For example, the following programs compare the \CFA and C I/O mechanisms.
260\begin{quote2}
261\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
262\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
263\begin{lstlisting}
264#include <fstream>
265int main( void ) {
266        int x = 0, y = 1, z = 2;
267        sout | x | y | z | endl;
268}
269\end{lstlisting}
270&
271\begin{lstlisting}
272#include <stdio.h>
273int main( void ) {
274        int x = 0, y = 1, z = 2;
275        printf( "%d %d %d\n", x, y, z );
276}
277\end{lstlisting}
278\end{tabular}
279\end{quote2}
280Both programs output the same result.
281While the \CFA I/O looks similar to the \CC style of output, there are several important differences, such as automatic spacing between variables as in Python (see also~\VRef{s:IOLibrary}).
282
283This document is a reference manual for the \CFA programming language, targeted at \CFA programmers.
284Implementers may also refer to the \CFA Programming Language Specification for details about the language syntax and semantics.
285In its current state, this document covers the intended core features of the language.
286Changes to the syntax and additional features are expected to be included in later revisions.
287% For additional information, see \url{http://wiki.do-lang.org}.
288
289
290\section{History}
291
292The \CFA project started with K-W C~\cite{Till89,Buhr94a}, which extended C with new declaration syntax, multiple return values from routines, and extended assignment capabilities using the notion of tuples.
293(See~\cite{Werther96} for some similar work, but for \CC.)
294The original \CFA project~\cite{Ditchfield92} extended the C type system with parametric polymorphism and overloading, as opposed to the \CC approach of object-oriented extensions to the C type-system.
295A first implementation of the core Cforall language was created~\cite{Bilson03,Esteves04}, but at the time there was little interesting in extending C, so work did not continue.
296As the saying goes, ``What goes around, comes around'', and there is now renewed interest in the C programming language, so the \CFA project has been restarted.
297
298
299\section{Motivation: Why fix C?}
300
301Even with all its problems, C is a very popular programming language because it allows writing software at virtually any level in a computer system without restriction.
302For systems programming, where direct access to hardware and dealing with real-time issues is a requirement, C is usually the language of choice.
303As well, there are millions of lines of C legacy code, forming the base for many software development projects (especially on UNIX systems).
304The TIOBE index (\url{http://www.tiobe.com/tiobe_index}) for March 2016 shows programming-language popularity, with Java 20.5\%, C 14.5\%, \CC 6.7\%, \CS 4.3\%, Python 4.3\%, and all other programming languages below 3\%.
305Hence, C is still an extremely important programming language, with double the usage of \CC, where \CC itself is largely C code.
306Finally, love it or hate it, C has been an important and influential part of computer science for 40 years and it appears it will continue to be for many more years.
307Unfortunately, C has too many problems and omissions to make it an acceptable programming language for modern needs.
308
309The goal of this project is to engineer modern language features into C in an evolutionary rather than revolutionary way.
310\CC~\cite{c++,ANSI14:C++} is an example of a similar project;
311however, it largely extended the language, and did not address existing problems.\footnote{%
312Two important existing problems addressed were changing the type of character literals from \lstinline@int@ to \lstinline@char@ and enumerator from \lstinline@int@ to the type of its enumerators.}
313Fortran~\cite{Fortran08}, Ada~\cite{Ada12}, and Cobol~\cite{Cobol14} are examples of programming languages that took an evolutionary approach, where modern language features are added and problems fixed within the framework of the existing language.
314Java~\cite{Java8}, Go~\cite{Go}, Rust~\cite{Rust} and 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.
315These languages have different syntax and semantics from C, and do not interoperate directly with C, largely because of garbage collection.
316As a result, there is a significant learning curve to move to these languages, and C legacy-code must be complete rewritten.
317These costs can be prohibitive for many companies with a large software base in C/\CC, and many programmers that require retraining to a new programming language.
318
319The result of this project is a language that is largely backwards compatible with C11~\cite{C11}, but containing many modern language features and fixing some of the well known C problems.
320Without significant extension to the C programming language, C will be unable to cope with the needs of modern programming problems and programmers;
321as a result, it will fade into disuse.
322Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language.
323While 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.
324While 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.
325
326
327\section{Interoperability}
328
329\CFA is designed to integrate well with existing C programs and libraries.
330The most important feature of interoperability is to use the same calling conventions, so there is no overhead to call existing C routines.
331This feature allows users of \CFA to take advantage of the existing panoply of C libraries from inside their \CFA code.
332In fact, one of the biggest issues for any new programming language is establishing a minimum level of library code to support a large body of activities.
333Programming-language developers often state that adequate library support costs many times more than designing and implementing the language itself.
334Like \CC, \CFA 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.
335
336However, it is necessary to differentiate between C and \CFA code because of name overloading, as for \CC.
337For example, the C math-library provides the following routines for computing the absolute value of the basic type: \lstinline@abs@, \lstinline@labs@, \lstinline@llabs@, \lstinline@fabs@, \lstinline@fabsf@, \lstinline@fabsl@, \lstinline@cabsf@, \lstinline@cabs@, and \lstinline@cabsl@.
338Whereas, \CFA wraps each of these routines into one with the common name \lstinline@abs@.
339\begin{lstlisting}
340extern "C" {
341#include <stdlib.h>                     // provide C prototype for integer "abs" routine
342} // extern "C"
343
344char abs( char );
345long int abs( long int );       // @{\CFA}@ overload name "abs" for other types
346long long int abs( long long int );
347float abs( float );
348double abs( double );
349long double abs( long double );
350float _Complex abs( float _Complex );
351double _Complex abs( double _Complex );
352long double _Complex abs( long double _Complex );
353\end{lstlisting}
354The problem is the name clash between the library routine \lstinline@abs@ and the \CFA names \lstinline@abs@.
355Hence, names appearing in an \lstinline@extern "C"@ block have \newterm{C linkage}.
356Then overloading polymorphism uses a mechanism called \newterm{name mangling} to create unique names that are different from C names, which are not mangled.
357Hence, 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.
358There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type.
359This example strongly illustrates a core idea in \CFA: \emph{the power of a name}.
360The name ``\lstinline@abs@'' evokes the notion of absolute value, and many mathematical types provide the notion of absolute value.
361Hence, knowing the name \lstinline@abs@ should be sufficient to apply it to any type where it is applicable.
362The time savings and safety of using one name uniformly versus @N@ unique names should not be underestimated.
363
364
365\section{Compiling \CFA}
366
367The command \lstinline@cfa@ is used to compile \CFA program(s).
368This command works like the GNU \lstinline@gcc@ command, e.g.:
369\begin{lstlisting}
370cfa [ gcc-options ] C/@{\CFA}@-files [ assembler/loader-files ]
371\end{lstlisting}
372The following additional option is available:
373\begin{description}
374\item
375\hspace*{-4pt}\lstinline@-CFA@
376Only 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.
377\end{description}
378
379
380\section{Underscores in Constants}
381
382Numeric constants are extended to allow \Index{underscore}s within constants\index{constant!underscore}, e.g.:
383\begin{lstlisting}
3842_147_483_648;                          // decimal constant
38556_ul;                                          // decimal unsigned long constant
3860_377;                                          // octal constant
3870x_ff_ff;                                       // hexadecimal constant
3880x_ef3d_aa5c;                           // hexadecimal constant
3893.141_592_654;                          // floating point constant
39010_e_+1_00;                                     // floating point constant
3910x_ff_ff_p_3;                           // hexadecimal floating point
3920x_1.ffff_ffff_p_128_l;         // hexadecimal floating point long constant
393L_"\x_ff_ee";                           // wide character constant
394\end{lstlisting}
395The rules for placement of underscores is as follows:
396\begin{enumerate}
397\item
398A sequence of underscores is disallowed, e.g., \lstinline@12__34@ is invalid.
399\item
400Underscores may only appear within a sequence of digits (regardless of the digit radix).
401In other words, an underscore cannot start or end a sequence of digits, e.g., \lstinline@_1@, \lstinline@1_@ and \lstinline@_1_@ are invalid (actually, the 1st and 3rd examples are identifier names).
402\item
403A numeric prefix may end with an underscore;
404a numeric infix may begin and/or end with an underscore;
405a numeric suffix may begin with an underscore.
406For example, the octal \lstinline@0@ or hexadecimal \lstinline@0x@ prefix may end with an underscore \lstinline@0_377@ or \lstinline@0x_ff@;
407the exponent infix \lstinline@E@ may start or end with an underscore \lstinline@1.0_E10@, \lstinline@1.0E_10@ or \lstinline@1.0_E_10@;
408the type suffixes \lstinline@U@, \lstinline@L@, etc. may start with an underscore \lstinline@1_U@, \lstinline@1_ll@ or \lstinline@1.0E10_f@.
409\end{enumerate}
410It is significantly easier to read and type long constants when they are broken up into smaller groupings (most cultures use comma or period among digits for the same purpose).
411This extension is backwards compatible, matches with the use of underscore in variable names, and appears in Ada and Java.
412
413
414\section{Declarations}
415\label{s:Declarations}
416
417C declaration syntax is notoriously confusing and error prone.
418For example, many C programmers are confused by a declaration as simple as:
419\begin{lstlisting}
420int *x[ 10 ]
421\end{lstlisting}
422Is this a pointer to an array of 10 integers or an array of 10 pointers to integers?
423Another 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.
424For example, a routine returning a pointer to an array of integers is defined and used in the following way:
425\begin{lstlisting}
426int (*f())[ 10 ] {...};
427... (*f())[ 3 ] += 1;           // definition mimics usage
428\end{lstlisting}
429Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
430While attempting to make the two contexts consistent was a laudable goal, it has not worked out in practice.
431
432\CFA provides its own type, variable and routine declarations, using a slightly different syntax.
433The new declarations place modifiers to the left of the base type, while C declarations place modifiers to the right of the base type.
434The only exception is bit field specification, which always appear to the right of the base type.
435C and the new \CFA declarations may appear together in the same program block, but cannot be mixed within a specific declaration.
436Unsupported are K\&R C declarations where the base type defaults to \lstinline@int@, if no type is specified\footnote{
437At 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}},
438e.g.:
439\begin{lstlisting}
440x;                                      // int x
441*y;                                     // int *y
442f( p1, p2 );            // int f( int p1, int p2 );
443f( p1, p2 ) {}          // int f( int p1, int p2 ) {}
444\end{lstlisting}
445
446In \CFA declarations, the same tokens are used as in C: the character \lstinline@*@ is used to indicate a pointer, square brackets \lstinline@[@\,\lstinline@]@ are used to represent an array, and parentheses \lstinline@()@ are used to indicate a routine parameter.
447However, unlike C, \CFA type declaration tokens are specified from left to right and the entire type specification is distributed across all variables in the declaration list.
448For instance, variables \lstinline@x@ and \lstinline@y@ of type pointer to integer are defined in \CFA as follows:
449\begin{quote2}
450\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
451\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
452\begin{lstlisting}
453* int x, y;
454\end{lstlisting}
455&
456\begin{lstlisting}
457int *x, *y;
458\end{lstlisting}
459\end{tabular}
460\end{quote2}
461Other examples are:
462\begin{quote2}
463\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
464\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
465\begin{lstlisting}
466[ 10 ] int z;
467[ 10 ] * char w;
468* [ 10 ] double v;
469struct s {
470int f0:3;
471        * int f1;
472        [ 10 ] * int f2;
473};
474\end{lstlisting}
475&
476\begin{lstlisting}
477int z[ 10 ];
478char *w[ 10 ];
479double (*v)[ 10 ];
480struct s {
481        int f0:3;
482        int *f1;
483        int *f2[ 10 ]
484};
485\end{lstlisting}
486&
487\begin{lstlisting}
488// array of 10 integers
489// array of 10 pointers to char
490// pointer to array of 10 doubles
491
492// common bit field syntax
493
494
495
496\end{lstlisting}
497\end{tabular}
498\end{quote2}
499
500As stated above, the two styles of declaration may appear together in the same block.
501Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
502Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems.
503In general, mixing declaration styles in a routine or even a translation unit is not recommended, as it makes a program more difficult to read.
504Therefore, it is suggested that an entire translation unit be written in one declaration style or the other.
505
506All type qualifiers, i.e., \lstinline@const@ and \lstinline@volatile@, are used in the normal way with the new declarations but appear left to right, e.g.:
507\begin{quote2}
508\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
509\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
510\begin{lstlisting}
511const * const int x;
512const * [ 10 ] const int y;
513\end{lstlisting}
514&
515\begin{lstlisting}
516int const * const x;
517const int (* const y)[ 10 ]
518\end{lstlisting}
519&
520\begin{lstlisting}
521// const pointer to const integer
522// const pointer to array of 10 const integers
523\end{lstlisting}
524\end{tabular}
525\end{quote2}
526All declaration qualifiers, i.e., \lstinline@extern@, \lstinline@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}
527The 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}} e.g.:
528\begin{quote2}
529\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
530\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
531\begin{lstlisting}
532extern [ 10 ] int x;
533static * const int y;
534\end{lstlisting}
535&
536\begin{lstlisting}
537int extern x[ 10 ];
538const int static *y;
539\end{lstlisting}
540&
541\begin{lstlisting}
542// externally visible array of 10 integers
543// internally visible pointer to constant int
544\end{lstlisting}
545\end{tabular}
546\end{quote2}
547
548
549\section{Type Operators}
550
551The new declaration syntax can be used in other contexts where types are required, e.g., casts and the pseudo-routine \lstinline@sizeof@:
552\begin{quote2}
553\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
554\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
555\begin{lstlisting}
556y = (* int)x;
557i = sizeof([ 10 ] * int);
558\end{lstlisting}
559&
560\begin{lstlisting}
561y = (int *)x;
562i = sizeof(int *[ 10 ]);
563\end{lstlisting}
564\end{tabular}
565\end{quote2}
566
567
568\section{Routine Definition}
569
570\CFA also supports a new syntax for routine definition, as well as ISO C and K\&R routine syntax.
571The point of the new syntax is to allow returning multiple values from a routine~\cite{CLU,Galletly96}, e.g.:
572\begin{lstlisting}
573[ int o1, int o2, char o3 ] f( int i1, char i2, char i3 ) {
574        @\emph{routine body}@
575}
576\end{lstlisting}
577where routine \lstinline@f@ has three output (return values) and three input parameters.
578Existing C syntax cannot be extended with multiple return types because it is impossible to embed a single routine name within multiple return type specifications.
579
580In detail, the brackets, \lstinline@[]@, enclose the result type, where each return value is named and that name is a local variable of the particular return type.\footnote{
581Michael Tiemann, with help from Doug Lea, provided named return values in g++, circa 1989.}
582The value of each local return variable is automatically returned at routine termination.
583Declaration qualifiers can only appear at the start of a routine definition, e.g.:
584\begin{lstlisting}
585extern [ int x ] g( int y ) {}
586\end{lstlisting}
587Lastly, if there are no output parameters or input parameters, the brackets and/or parentheses must still be specified;
588in 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:
589\begin{lstlisting}
590[ ] g();                                        // no input or output parameters
591[ void ] g( void );                     // no input or output parameters
592\end{lstlisting}
593
594Routine f is called as follows:
595\begin{lstlisting}
596[ i, j, ch ] = f( 3, 'a', ch );
597\end{lstlisting}
598The list of return values from f and the grouping on the left-hand side of the assignment is called a tuple and discussed in Section 12.
599
600\CFA style declarations cannot be used to declare parameters for K\&R style routine definitions because of the following ambiguity:
601\begin{lstlisting}
602int (*f(x))[ 10 ] int x; {}
603\end{lstlisting}
604The string ``\lstinline@int (*f(x))[ 10 ]@'' declares a K\&R style routine of type returning a pointer to an array of 10 integers, while the string ``\lstinline@[ 10 ] int x@'' declares a \CFA style parameter x of type array of 10 integers.
605Since the strings overlap starting with the open bracket, \lstinline@[@, there is an ambiguous interpretation for the string.
606As well, \CFA-style declarations cannot be used to declare parameters for C-style routine-definitions because of the following ambiguity:
607\begin{lstlisting}
608typedef int foo;
609int f( int (* foo) );           // foo is redefined as a parameter name
610\end{lstlisting}
611The string ``\lstinline@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.
612The redefinition of a type name in a parameter list is the only context in C where the character \lstinline@*@ can appear to the left of a type name, and \CFA relies on all type modifier characters appearing to the right of the type name.
613The 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.
614
615C-style declarations can be used to declare parameters for \CFA style routine definitions, e.g.:
616\begin{lstlisting}
617[ int ] f( * int, int * );      // returns an integer, accepts 2 pointers to integers
618[ * int, int * ] f( int );      // returns 2 pointers to integers, accepts an integer
619\end{lstlisting}
620The 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:
621\begin{lstlisting}
622#define ptoa( n, d ) int (*n)[ d ]
623int f( ptoa(p,10) ) ...         // expands to int f( int (*p)[ 10 ] )
624[ int ] f( ptoa(p,10) ) ...     // expands to [ int ] f( int (*p)[ 10 ] )
625\end{lstlisting}
626Again, programmers are highly encouraged to use one declaration form or the other, rather than mixing the forms.
627
628
629\subsection{Returning Values}
630
631Named return values handle the case where it is necessary to define a local variable whose value is then returned in a \lstinline@return@ statement, as in:
632\begin{lstlisting}
633int f() {
634        int x;
635        ... x = 0; ... x = y; ...
636        return x;
637}
638\end{lstlisting}
639Because the value in the return variable is automatically returned when a \CFA routine terminates, the \lstinline@return@ statement \emph{does not} contain an expression, as in:
640\begin{lstlisting}
641[ int x ] f() {
642        ... x = 0; ... x = y; ...
643        return; // implicitly return x
644}
645\end{lstlisting}
646When the return is encountered, the current value of \lstinline@x@ is returned to the calling routine.
647As well, ``falling off the end'' of a routine without a \lstinline@return@ statement is permitted, as in:
648\begin{lstlisting}
649[ int x ] f() {
650        ... x = 0; ... x = y; ...
651} // implicitly return x
652\end{lstlisting}
653In this case, the current value of \lstinline@x@ is returned to the calling routine just as if a \lstinline@return@ had been encountered.
654
655
656\subsection{Routine Prototype}
657
658The syntax of the new routine prototype declaration follows directly from the new routine definition syntax;
659as well, parameter names are optional, e.g.:
660\begin{lstlisting}
661[ int x ] f ();                         // returning int with no parameters
662[ * int ] g (int y);            // returning pointer to int with int parameter
663[ ] h (int,char);                       // returning no result with int and char parameters
664[ * int,int ] j (int);          // returning pointer to int and int, with int parameter
665\end{lstlisting}
666This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
667It 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}), e.g.:
668\begin{quote2}
669\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
670\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
671\begin{lstlisting}
672[ int ] f(int), g;
673\end{lstlisting}
674&
675\begin{lstlisting}
676int f(int), g(int);
677\end{lstlisting}
678\end{tabular}
679\end{quote2}
680Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} e.g.:
681\begin{lstlisting}
682extern [ int ] f (int);
683static [ int ] g (int);
684\end{lstlisting}
685
686
687\section{Routine Pointers}
688
689The syntax for pointers to \CFA routines specifies the pointer name on the right, e.g.:
690\begin{lstlisting}
691* [ int x ] () fp;                      // pointer to routine returning int with no parameters
692* [ * int ] (int y) gp;         // pointer to routine returning pointer to int with int parameter
693* [ ] (int,char) hp;            // pointer to routine returning no result with int and char parameters
694* [ * int,int ] (int) jp;       // pointer to routine returning pointer to int and int, with int parameter
695\end{lstlisting}
696While parameter names are optional, \emph{a routine name cannot be specified};
697for example, the following is incorrect:
698\begin{lstlisting}
699* [ int x ] f () fp;            // routine name ``f'' is not allowed
700\end{lstlisting}
701
702
703\section{Named and Default Arguments}
704
705Named and default arguments~\cite{Hardgrave76}.\footnote{
706Francez~\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.}
707are two mechanisms to simplify routine call.
708Both mechanisms are discussed with respect to \CFA.
709\begin{description}
710\item[Named (or Keyword) Arguments:]
711provide the ability to specify an argument to a routine call using the parameter name rather than the position of the parameter.
712For example, given the routine:
713\begin{lstlisting}
714void p( int x, int y, int z ) {...}
715\end{lstlisting}
716a positional call is:
717\begin{lstlisting}
718p( 4, 7, 3 );
719\end{lstlisting}
720whereas a named (keyword) call may be:
721\begin{lstlisting}
722p( z : 3, x : 4, y : 7 ); // rewrite $\Rightarrow$ p( 4, 7, 3 )
723\end{lstlisting}
724Here the order of the arguments is unimportant, and the names of the parameters are used to associate argument values with the corresponding parameters.
725The compiler rewrites a named call into a positional call.
726The advantages of named parameters are:
727\begin{itemize}
728\item
729Remembering the names of the parameters may be easier than the order in the routine definition.
730\item
731Parameter names provide documentation at the call site (assuming the names are descriptive).
732\item
733Changes can be made to the order or number of parameters without affecting the call (although the call must still be recompiled).
734\end{itemize}
735
736Unfortunately, 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.
737For example, the following routine prototypes and definition are all valid.
738\begin{lstlisting}
739void p( int, int, int );                        // equivalent prototypes
740void p( int x, int y, int z );
741void p( int y, int x, int z );
742void p( int z, int y, int x );
743void p( int q, int r, int s ) {}        // match with this definition
744\end{lstlisting}
745Forcing matching parameter names in routine prototypes with corresponding routine definitions is possible, but goes against a strong tradition in C programming.
746Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports.
747The former is easy to do, while the latter is more complex.
748Currently, \CFA does \emph{not} attempt to support named arguments.
749
750\item[Default Arguments]
751provide the ability to associate a default value with a parameter so it can be optionally specified in the argument list.
752For example, given the routine:
753\begin{lstlisting}
754void p( int x = 1, int y = 2, int z = 3 ) {...}
755\end{lstlisting}
756the allowable positional calls are:
757\begin{lstlisting}
758p();                            // rewrite $\Rightarrow$ p( 1, 2, 3 )
759p( 4 );                         // rewrite $\Rightarrow$ p( 4, 2, 3 )
760p( 4, 4 );                      // rewrite $\Rightarrow$ p( 4, 4, 3 )
761p( 4, 4, 4 );           // rewrite $\Rightarrow$ p( 4, 4, 4 )
762// empty arguments
763p(  , 4, 4 );           // rewrite $\Rightarrow$ p( 1, 4, 4 )
764p( 4,  , 4 );           // rewrite $\Rightarrow$ p( 4, 2, 4 )
765p( 4, 4,   );           // rewrite $\Rightarrow$ p( 4, 4, 3 )
766p( 4,  ,   );           // rewrite $\Rightarrow$ p( 4, 2, 3 )
767p(  , 4,   );           // rewrite $\Rightarrow$ p( 1, 4, 3 )
768p(  ,  , 4 );           // rewrite $\Rightarrow$ p( 1, 2, 4 )
769p(  ,  ,   );           // rewrite $\Rightarrow$ p( 1, 2, 3 )
770\end{lstlisting}
771Here the missing arguments are inserted from the default values in the parameter list.
772The compiler rewrites missing default values into explicit positional arguments.
773The advantages of default values are:
774\begin{itemize}
775\item
776Routines with a large number of parameters are often very generalized, giving a programmer a number of different options on how a computation is performed.
777For many of these kinds of routines, there are standard or default settings that work for the majority of computations.
778Without 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.
779\item
780When a routine's interface is augmented with new parameters, it extends the interface providing generalizability\footnote{
781``It should be possible for the implementor of an abstraction to increase its generality.
782So long as the modified abstraction is a generalization of the original, existing uses of the abstraction will not require change.
783It 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.
784This 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}}
785(somewhat like the generalization provided by inheritance for classes).
786That is, all existing calls are still valid, although the call must still be recompiled.
787\end{itemize}
788The only disadvantage of default arguments is that unintentional omission of an argument may not result in a compiler-time error.
789Instead, a default value is used, which may not be the programmer's intent.
790
791Default values may only appear in a prototype versus definition context:
792\begin{lstlisting}
793void p( int x, int y = 2, int z = 3 );          // prototype: allowed
794void p( int, int = 2, int = 3 );                        // prototype: allowed
795void p( int x, int y = 2, int z = 3 ) {}        // definition: not allowed
796\end{lstlisting}
797The reason for this restriction is to allow separate compilation.
798Multiple prototypes with different default values is an error.
799\end{description}
800
801Ellipse (``...'') arguments present problems when used with default arguments.
802The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities:
803\begin{lstlisting}
804p( /* positional */, . . ., /* named */ );
805p( /* positional */, /* named */, . . . );
806\end{lstlisting}
807While it is possible to implement both approaches, the first possibly is more complex than the second, e.g.:
808\begin{lstlisting}
809p( int x, int y, int z, . . . );
810p( 1, 4, 5, 6, z : 3, y : 2 ); // assume p( /* positional */, . . ., /* named */ );
811p( 1, z : 3, y : 2, 4, 5, 6 ); // assume p( /* positional */, /* named */, . . . );
812\end{lstlisting}
813In 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.
814Hence, this approach seems significantly more difficult, and hence, confusing and error prone.
815In the second call, the named arguments separate the positional and ellipse arguments, making it trivial to read the call.
816
817The problem is exacerbated with default arguments, e.g.:
818\begin{lstlisting}
819void p( int x, int y = 2, int z = 3. . . );
820p( 1, 4, 5, 6, z : 3 );         // assume p( /* positional */, . . ., /* named */ );
821p( 1, z : 3, 4, 5, 6 );         // assume p( /* positional */, /* named */, . . . );
822\end{lstlisting}
823The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments;
824therefore, argument 5 subsequently conflicts with the named argument z : 3.
825In 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.
826For these reasons, \CFA requires named arguments before ellipse arguments.
827Finally, 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.
828
829Default arguments and overloading (see Section 24) are complementary.
830While in theory default arguments can be simulated with overloading, as in:
831\begin{quote2}
832\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
833\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{default arguments}}  & \multicolumn{1}{c}{\textbf{overloading}}      \\
834\begin{lstlisting}
835void p( int x, int y = 2, int z = 3 ) {...}
836
837
838\end{lstlisting}
839&
840\begin{lstlisting}
841void p( int x, int y, int z ) {...}
842void p( int x ) { p( x, 2, 3 ); }
843void p( int x, int y ) { p( x, y, 3 ); }
844\end{lstlisting}
845\end{tabular}
846\end{quote2}
847the number of required overloaded routines is linear in the number of default values, which is unacceptable growth.
848In general, overloading should only be used over default arguments if the body of the routine is significantly different.
849Furthermore, overloading cannot handle accessing default arguments in the middle of a positional list, via a missing argument, such as:
850\begin{lstlisting}
851p( 1, /* default */, 5 );               // rewrite $\Rightarrow$ p( 1, 2, 5 )
852\end{lstlisting}
853
854Given the \CFA restrictions above, both named and default arguments are backwards compatible.
855\CC only supports default arguments;
856Ada supports both named and default arguments.
857
858
859\section{Type/Routine Nesting}
860
861Nesting of types and routines is useful for controlling name visibility (\newterm{name hiding}).
862
863
864\subsection{Type Nesting}
865
866C allows \Index{type nesting}, but the nested types are hoisted\index{type!hoisting} (refactored) into the enclosing scope.
867\begin{quote2}
868\begin{tabular}{@{}l@{\hspace{30pt}}l|l@{}}
869\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{C Type Nesting}}     & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}}      & \multicolumn{1}{|c}{\textbf{\CFA}}    \\
870\hline
871\begin{lstlisting}
872struct S {
873        enum C { R, G, B };
874        struct T {
875                union U { int i, j; };
876                enum C c;
877                short int i, j;
878        };
879        struct T t;
880} s;
881
882int fred() {
883        s.t.c = R;
884        struct T t = { R, 1, 2 };
885        enum C c;
886        union U u;
887}
888\end{lstlisting}
889&
890\begin{lstlisting}
891enum C { R, G, B };
892union U { int i, j; };
893struct T {
894        enum C c;
895        short int i, j;
896};
897struct S {
898        struct T t;
899} s;
900       
901
902
903
904
905
906
907\end{lstlisting}
908&
909\begin{lstlisting}
910struct S {
911        enum C { R, G, B };
912        struct T {
913                union U { int i, j; };
914                enum C c;
915                short int i, j;
916        };
917        struct T t;
918} s;
919
920int fred() {
921        s.t.c = S.R;
922        struct S.T t = { S.R, 1, 2 };
923        enum S.C c;
924        union S.T.U u;
925}
926\end{lstlisting}
927\end{tabular}
928\end{quote2}
929
930\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \CC.
931Nested types are not hoisted and can be referenced using the field selection operator ``\lstinline@.@'', unlike the \CC scope-resolution operator ``\lstinline@::@''.
932Given that nested types in C are equivalent to not using them, i.e., they are essentially useless, it is unlikely there are any realistic usages that break because of this incompatibility.
933
934
935\subsection{Routine Nesting}
936
937While \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.
938For example, the C quick-sort is wrapped into the following polymorphic \CFA routine:
939\begin{lstlisting}
940forall( otype T | { int ?<?( T, T ); } )
941void qsort( const T * arr, size_t dimension );
942\end{lstlisting}
943which can be used to sort in ascending and descending order by locally redefining the less-than operator into greater-than.
944\begin{lstlisting}
945const unsigned int size = 10;
946int a[size];
947
948qsort( a, size );               // ascending order using built in ?<?
949{                                               // descending order by local redefinition
950        int ?<?( int a, int b ) { return a > b; } // nested routine
951        qsort( a, size );
952}
953\end{lstlisting}
954
955
956\section{Incompatible}
957
958The following incompatibles exist between C and \CFA, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
959
960\begin{enumerate}
961\item
962Change type of character literal \lstinline@int@ to \lstinline@char@.
963This change allows overloading differentiation argument type matching, e.g.:
964\begin{lstlisting}
965int function( int i );
966int function( char c );
967function( 'x' );
968\end{lstlisting}
969It is preferable that this call match the second version of function rather than the first. \\
970Effect on original feature: Change to semantics of well-defined feature. ISO C programs which depend on
971\begin{lstlisting}
972sizeof('x') == sizeof(int)
973\end{lstlisting}
974will not work the same as C++ programs. \\
975Difficulty of converting: Simple. \\
976How widely used: Programs which depend upon sizeof('x') are probably rare.
977
978\item
979Change: String literals made \lstinline@const@ \\
980The type of a string literal is changed from \lstinline@array of char@ to \lstinline@array of const char@.
981The type of a wide string literal is changed from \lstinline@array of wchar_t@ to \lstinline@array of const wchar_t@. \\
982Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.
983Effect on original feature: Change to semantics of well-defined feature. \\
984Difficulty of converting: Simple syntactic transformation, because string literals can be converted to \lstinline@char*;@ (4.2).
985The most common cases are handled by a new but deprecated standard conversion:
986\begin{lstlisting}
987char* p = "abc"; // valid in C, deprecated in C++
988char* q = expr ? "abc" : "de"; // valid in C, invalid in C++
989\end{lstlisting}
990How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.
991
992\item
993Change: C++ does not have \emph{tentative definitions} as in C.
994E.g., at file scope,
995\begin{lstlisting}
996int i;
997int i;
998\end{lstlisting}
999is valid in C, invalid in C++.
1000This makes it impossible to define mutually referential file-local static
1001objects, if initializers are restricted to the syntactic forms of C. For example,
1002\begin{lstlisting}
1003struct X { int i; struct X *next; };
1004static struct X a;
1005static struct X b = { 0, &a };
1006static struct X a = { 1, &b };
1007\end{lstlisting}
1008Rationale: This avoids having different initialization rules for builtin types and userdefined types.
1009Effect on original feature: Deletion of semantically welldefined feature. \\
1010Difficulty of converting: Semantic transformation.
1011In C++, the initializer for one of a set of mutuallyreferential filelocal static objects must invoke a function call to achieve the initialization.
1012How widely used: Seldom.
1013
1014\item
1015Change: A struct is a scope in C++, not in C
1016Rationale: Class scope is crucial to C++, and a struct is a class.
1017Effect on original feature: Change to semantics of well-defined feature.
1018Difficulty of converting: Semantic transformation.
1019How widely used: C programs use struct extremely frequently, but the change is only noticeable when
1020struct, enumeration, or enumerator names are referred to outside the struct. The latter is probably
1021rare.
1022
1023\item
1024Change: In C++, the name of a nested class is local to its enclosing class.
1025In C the name of the nested class belongs to the same scope as the name of the outermost enclosing class
1026Example:
1027\begin{lstlisting}
1028struct X {
1029struct Y { /* ... */ } y;
1030};
1031struct Y yy; // valid C, invalid C++
1032\end{lstlisting}
1033Rationale: C++ classes have member functions which require that classes establish scopes. The C rule
1034would leave classes as an incomplete scope mechanism which would prevent C++ programmers from maintaining
1035locality within a class. A coherent set of scope rules for C++ based on the C rule would be very
1036complicated and C++ programmers would be unable to predict reliably the meanings of nontrivial examples
1037involving nested or local functions.
1038Effect on original feature: Change of semantics of welldefined
1039feature.
1040Difficulty of converting: Semantic transformation. To make the struct type name visible in the scope of
1041the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing
1042struct is defined. Example:
1043\begin{lstlisting}
1044struct Y; // struct Y and struct X are at the same scope
1045struct X {
1046struct Y { /* ... */ } y;
1047};
1048\end{lstlisting}
1049All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of
1050the enclosing struct could be exported to the scope of the enclosing struct. Note: this is a consequence of
1051the difference in scope rules, which is documented in 3.3.
1052How widely used: Seldom.
1053\end{enumerate}
1054
1055
1056\section{Tuples}
1057
1058In C and \CFA, lists of elements appear in several contexts, such as the parameter list for a routine call.
1059(More contexts are added shortly.)
1060A list of such elements is called a tuple.
1061The general syntax of a tuple is:
1062\begin{lstlisting}
1063[ $\emph{exprlist}$ ]
1064\end{lstlisting}
1065where \lstinline@$\emph{exprlist}$@ is a list of one or more expressions separated by commas.
1066The brackets, \lstinline$[]$, allow differentiating between tuples and expressions containing the C comma operator.
1067The following are examples of tuples:
1068\begin{lstlisting}
1069[ x, y, z ]
1070[ 2 ]
1071[ v+w, x*y, 3.14159, f() ]
1072\end{lstlisting}
1073Tuples are permitted to contain sub-tuples (i.e., nesting), such as \lstinline@[ [ 14, 21 ], 9 ]@, which is a 2-element tuple whose first element is itself a tuple.
1074Note, a tuple is not a record (structure);
1075a record denotes a single value with substructure, whereas a tuple is multiple values with no substructure (see flattening coercion in Section 12.1).
1076In essence, tuples are largely a compile time phenomenon, having little or no runtime presence.
1077
1078Tuples can be organized into compile-time tuple variables;
1079these variables are of \newterm{tuple type}.
1080Tuple variables and types can be used anywhere lists of conventional variables and types can be used.
1081The general syntax of a tuple type is:
1082\begin{lstlisting}
1083[ @\emph{typelist}@ ]
1084\end{lstlisting}
1085where \lstinline@$\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.
1086Examples of tuple types include:
1087\begin{lstlisting}
1088[ unsigned int, char ]
1089[ double, double, double ]
1090[ * int, int * ]                // mix of CFA and ANSI
1091[ * [ 10 ] int, * * char, * [ [ int, int ] ] (int, int) ]
1092\end{lstlisting}
1093Like tuples, tuple types may be nested, such as \lstinline@[ [ int, int ], int ]@, which is a 2-element tuple type whose first element is itself a tuple type.
1094
1095Examples of declarations using tuple types are:
1096\begin{lstlisting}
1097[ int, int ] x;                 // 2 element tuple, each element of type int
1098* [ char, char ] y;             // pointer to a 2 element tuple
1099[ [ int, int ] ] z ([ int, int ]);
1100\end{lstlisting}
1101The 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.
1102
1103As mentioned, tuples can appear in contexts requiring a list of value, such as an argument list of a routine call.
1104In unambiguous situations, the tuple brackets may be omitted, e.g., a tuple that appears as an argument may have its
1105square brackets omitted for convenience; therefore, the following routine invocations are equivalent:
1106\begin{lstlisting}
1107f( [ 1, x+2, fred() ] );
1108f( 1, x+2, fred() );
1109\end{lstlisting}
1110Also, 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.
1111For example, the following are all legal:
1112\begin{lstlisting}
1113[ int, int ] w1;
1114[ int, int, int ] w2;
1115[ void ] f (int, int, int); /* three input parameters of type int */
1116[ void ] g ([ int, int, int ]); /* 3 element tuple as input */
1117f( [ 1, 2, 3 ] );
1118f( w1, 3 );
1119f( 1, w1 );
1120f( w2 );
1121g( [ 1, 2, 3 ] );
1122g( w1, 3 );
1123g( 1, w1 );
1124g( w2 );
1125\end{lstlisting}
1126Note, in all cases 3 arguments are supplied even though the syntax may appear to supply less than 3. As mentioned, a
1127tuple does not have structure like a record; a tuple is simply converted into a list of components.
1128\begin{rationale}
1129The present implementation of \CFA does not support nested routine calls when the inner routine returns multiple values; i.e., a statement such as \lstinline@g( f() )@ is not supported.
1130Using a temporary variable to store the  results of the inner routine and then passing this variable to the outer routine works, however.
1131\end{rationale}
1132
1133A tuple can contain a C comma expression, provided the expression containing the comma operator is enclosed in parentheses.
1134For instance, the following tuples are equivalent:
1135\begin{lstlisting}
1136[ 1, 3, 5 ]
1137[ 1, (2, 3), 5 ]
1138\end{lstlisting}
1139The second element of the second tuple is the expression (2, 3), which yields the result 3.
1140This requirement is the same as for comma expressions in argument lists.
1141
1142Type qualifiers, i.e., const and volatile, may modify a tuple type.
1143The 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)], i.e., the qualifier is distributed across all of the types in the tuple, e.g.:
1144\begin{lstlisting}
1145const volatile [ int, float, const int ] x;
1146\end{lstlisting}
1147is equivalent to:
1148\begin{lstlisting}
1149[ const volatile int, const volatile float, const volatile int ] x;
1150\end{lstlisting}
1151Declaration qualifiers can only appear at the start of a \CFA tuple declaration4, e.g.:
1152\begin{lstlisting}
1153extern [ int, int ] w1;
1154static [ int, int, int ] w2;
1155\end{lstlisting}
1156\begin{rationale}
1157Unfortunately, C's syntax for subscripts precluded treating them as tuples.
1158The C subscript list has the form \lstinline@[i][j]...@ and not \lstinline@i, j, ...]@.
1159Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, e.g., \lstinline@f[g()]@ always means a single subscript value because there is only one set of brackets.
1160Fixing this requires a major change to C because the syntactic form \lstinline@M[i, j, k]@ already has a particular meaning: \lstinline@i, j, k@ is a comma expression.
1161\end{rationale}
1162
1163
1164\subsection{Tuple Coercions}
1165
1166There are four coercions that can be performed on tuples and tuple variables: closing, opening, flattening and structuring.
1167In addition, the coercion of dereferencing can be performed on a tuple variable to yield its value(s), as for other variables.
1168A \newterm{closing coercion} takes a set of values and converts it into a tuple value, which is a contiguous set of values, as in:
1169\begin{lstlisting}
1170[ int, int, int, int ] w;
1171w = [ 1, 2, 3, 4 ];
1172\end{lstlisting}
1173First the right-hand tuple is closed into a tuple value and then the tuple value is assigned.
1174
1175An \newterm{opening coercion} is the opposite of closing; a tuple value is converted into a tuple of values, as in:
1176\begin{lstlisting}
1177[ a, b, c, d ] = w
1178\end{lstlisting}
1179\lstinline@w@ is implicitly opened to yield a tuple of four values, which are then assigned individually.
1180
1181A \newterm{flattening coercion} coerces a nested tuple, i.e., 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:
1182\begin{lstlisting}
1183[ a, b, c, d ] = [ 1, [ 2, 3 ], 4 ];
1184\end{lstlisting}
1185First the right-hand tuple is flattened and then the values are assigned individually.
1186Flattening is also performed on tuple types.
1187For example, the type \lstinline@[ int, [ int, int ], int ]@ can be coerced, using flattening, into the type lstinline@[ int, int, int, int ]@.
1188
1189A \newterm{structuring coercion} is the opposite of flattening;
1190a tuple is structured into a more complex nested tuple.
1191For example, structuring the tuple \lstinline@[ 1, 2, 3, 4 ]@ into the tuple \lstinline@[ 1, [ 2, 3 ], 4 ]@ or the tuple type \lstinline@[ int, int, int, int ]@ into the tuple type \lstinline@[ int, [ int, int ], int ]@.
1192In the following example, the last assignment illustrates all the tuple coercions:
1193\begin{lstlisting}
1194[ int, int, int, int ] w = [ 1, 2, 3, 4 ];
1195int x = 5;
1196[ x, w ] = [ w, x ];            // all four tuple coercions
1197\end{lstlisting}
1198Starting on the right-hand tuple in the last assignment statement, w is opened, producing a tuple of four values;
1199therefore, the right-hand tuple is now the tuple \lstinline@[ [ 1, 2, 3, 4 ], 5 ]@.
1200This tuple is then flattened, yielding \lstinline@[ 1, 2, 3, 4, 5 ]@, which is structured into \lstinline@[ 1, [ 2, 3, 4, 5 ] ]@ to match the tuple type of the left-hand side.
1201The tuple \lstinline@[ 2, 3, 4, 5 ]@ is then closed to create a tuple value.
1202Finally, \lstinline@x@ is assigned \lstinline@1@ and \lstinline@w@ is assigned the tuple value using multiple assignment (see Section 14).
1203\begin{rationale}
1204A possible additional language extension is to use the structuring coercion for tuples to initialize a complex record with a tuple.
1205\end{rationale}
1206
1207
1208\section{Mass Assignment}
1209
1210\CFA permits assignment to several variables at once using mass assignment~\cite{CLU}.
1211Mass assignment has the following form:
1212\begin{lstlisting}
1213[ @\emph{lvalue}@, ..., @\emph{lvalue}@ ] = @\emph{expr}@;
1214\end{lstlisting}
1215The left-hand side is a tuple of \lstinline@$\emph{lvalues}$@, which is a list of expressions each yielding an address, i.e., any data object that can appear on the left-hand side of a conventional assignment statement.
1216\lstinline@$\emph{expr}$@ is any standard arithmetic expression.
1217Clearly, the types of the entities being assigned must be type compatible with the value of the expression.
1218
1219Mass assignment has parallel semantics, e.g., the statement:
1220\begin{lstlisting}
1221[ x, y, z ] = 1.5;
1222\end{lstlisting}
1223is equivalent to:
1224\begin{lstlisting}
1225x = 1.5; y = 1.5; z = 1.5;
1226\end{lstlisting}
1227This semantics is not the same as the following in C:
1228\begin{lstlisting}
1229x = y = z = 1.5;
1230\end{lstlisting}
1231as conversions between intermediate assignments may lose information.
1232A more complex example is:
1233\begin{lstlisting}
1234[ i, y[i], z ] = a + b;
1235\end{lstlisting}
1236which is equivalent to:
1237\begin{lstlisting}
1238t = a + b;
1239a1 = &i; a2 = &y[i]; a3 = &z;
1240*a1 = t; *a2 = t; *a3 = t;
1241\end{lstlisting}
1242The temporary \lstinline@t@ is necessary to store the value of the expression to eliminate conversion issues.
1243The temporaries for the addresses are needed so that locations on the left-hand side do not change as the values are assigned.
1244In this case, \lstinline@y[i]@ uses the previous value of \lstinline@i@ and not the new value set at the beginning of the mass assignment.
1245
1246
1247\section{Multiple Assignment}
1248
1249\CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}.
1250Multiple assignment has the following form:
1251\begin{lstlisting}
1252[ @\emph{lvalue}@, . . ., @\emph{lvalue}@ ] = [ @\emph{expr}@, . . ., @\emph{expr}@ ];
1253\end{lstlisting}
1254The left-hand side is a tuple of \lstinline@$\emph{lvalues}$@, and the right-hand side is a tuple of \lstinline@$\emph{expr}$@s.
1255Each \lstinline@$\emph{expr}$@ appearing on the righthand side of a multiple assignment statement is assigned to the corresponding \lstinline@$\emph{lvalues}$@ on the left-hand side of the statement using parallel semantics for each assignment.
1256An example of multiple assignment is:
1257\begin{lstlisting}
1258[ x, y, z ] = [ 1, 2, 3 ];
1259\end{lstlisting}
1260Here, the values \lstinline@1@, \lstinline@2@ and \lstinline@3@ are assigned, respectively, to the variables \lstinline@x@, \lstinline@y@ and \lstinline@z@.
1261 A more complex example is:
1262\begin{lstlisting}
1263[ i, y[ i ], z ] = [ 1, i, a + b ];
1264\end{lstlisting}
1265Here, the values \lstinline@1@, \lstinline@i@ and \lstinline@a + b@ are assigned to the variables \lstinline@i@, \lstinline@y[i]@ and \lstinline@z@, respectively.
1266 Note, the parallel semantics of
1267multiple assignment ensures:
1268\begin{lstlisting}
1269[ x, y ] = [ y, x ];
1270\end{lstlisting}
1271correctly interchanges (swaps) the values stored in \lstinline@x@ and \lstinline@y@.
1272The following cases are errors:
1273\begin{lstlisting}
1274[ a, b, c ] = [ 1, 2, 3, 4 ];
1275[ a, b, c ] = [ 1, 2 ];
1276\end{lstlisting}
1277because the number of entities in the left-hand tuple is unequal with the right-hand tuple.
1278
1279As 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;
1280both these examples produce indeterminate results:
1281\begin{lstlisting}
1282f( x++, x++ );                          // C routine call with side effects in arguments
1283[ v1, v2 ] = [ x++, x++ ];      // side effects in righthand side of multiple assignment
1284\end{lstlisting}
1285
1286
1287\section{Cascade Assignment}
1288
1289As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment.
1290Cascade assignment has the following form:
1291\begin{lstlisting}
1292@\emph{tuple}@ = @\emph{tuple}@ = ... = @\emph{tuple}@;
1293\end{lstlisting}
1294and it has the same parallel semantics as for mass and multiple assignment.
1295Some examples of cascade assignment are:
1296\begin{lstlisting}
1297x1 = y1 = x2 = y2 = 0;
1298[ x1, y1 ] = [ x2, y2 ] = [ x3, y3 ];
1299[ x1, y1 ] = [ x2, y2 ] = 0;
1300[ x1, y1 ] = z = 0;
1301\end{lstlisting}
1302As in C, the rightmost assignment is performed first, i.e., assignment parses right to left.
1303
1304
1305\section{Field Tuples}
1306
1307Tuples may be used to select multiple fields of a record by field name.
1308Its general form is:
1309\begin{lstlisting}
1310@\emph{expr}@ . [ @\emph{fieldlist}@ ]
1311@\emph{expr}@ -> [ @\emph{fieldlist}@ ]
1312\end{lstlisting}
1313\lstinline@$\emph{expr}$@ is any expression yielding a value of type record, e.g., \lstinline@struct@, \lstinline@union@.
1314Each element of \lstinline@$\emph{ fieldlist}$@ is an element of the record specified by \lstinline@$\emph{expr}$@.
1315A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is
1316the following:
1317\begin{lstlisting}
1318struct s {
1319        int f1, f2;
1320        char f3;
1321        double f4;
1322} v;
1323v.[ f3, f1, f2 ] = ['x', 11, 17 ];      // equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17
1324f( v.[ f3, f1, f2 ] );                          // equivalent to f( v.f3, v.f1, v.f2 )
1325\end{lstlisting}
1326Note, the fields appearing in a record-field tuple may be specified in any order;
1327also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple.
1328
1329If a field of a \lstinline@struct@ is itself another \lstinline@struct@, multiple fields of this subrecord can be specified using a nested record-field tuple, as in the following example:
1330\begin{lstlisting}
1331struct inner {
1332        int f2, f3;
1333};
1334struct outer {
1335        int f1;
1336        struct inner i;
1337        double f4;
1338} o;
1339
1340o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ];
1341\end{lstlisting}
1342
1343
1344\section{Labelled Break/Continue}
1345
1346While C provides \lstinline@break@ and \lstinline@continue@ statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
1347Unfortunately, this restriction forces programmers to use \lstinline@goto@ to achieve the equivalent for more than one level of nesting.
1348To prevent having to make this switch, the \lstinline@break@ and \lstinline@continue@ are extended with a target label to support static multi-level exit~\cite{Buhr85,Java}.
1349For the labelled \lstinline@break@, it is possible to specify which control structure is the target for exit, as in:
1350\begin{quote2}
1351\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
1352\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
1353\begin{lstlisting}
1354L1: for ( ... ) {
1355        L2: for ( ... ) {
1356                L3: for ( ... ) {
1357                        ... break L1; ...
1358                        ... break L2; ...
1359                        ... break L3; // or break
1360                }
1361        }
1362}
1363\end{lstlisting}
1364&
1365\begin{lstlisting}
1366for ( ... ) {
1367        for ( ... ) {
1368                for ( ... ) {
1369                        ... goto L1; ...
1370                        ... goto L2; ...
1371                        ... goto L3; // or break
1372                } L3: ;
1373        } L2: ;
1374} L1: ;
1375\end{lstlisting}
1376\end{tabular}
1377\end{quote2}
1378The inner most loop has three exit points, which cause termination of one or more of the three nested loops, respectively.
1379For the labelled \lstinline@continue@, it is possible to specify which control structure is the target for the next loop iteration, as in:
1380\begin{quote2}
1381\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
1382\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c}{\textbf{C}}        \\
1383\begin{lstlisting}
1384L1: for ( ... ) {
1385        L2: for ( ... ) {
1386                L3: for ( ... ) {
1387                        ... continue L1; ...
1388                        ... continue L2; ...
1389                        ... continue L3; ...
1390
1391                }
1392
1393        }
1394
1395}
1396\end{lstlisting}
1397&
1398\begin{lstlisting}
1399for ( ... ) {
1400        for ( ... ) {
1401                for ( ... ) {
1402                        ... goto L1; ...
1403                        ... goto L2; ...
1404                        ... goto L3; ...
1405                  L3: ;
1406                }
1407          L2: ;
1408        }
1409  L1: ;
1410}
1411\end{lstlisting}
1412\end{tabular}
1413\end{quote2}
1414The inner most loop has three restart points, which cause the next loop iteration to begin, respectively.
1415For both \lstinline@break@ and \lstinline@continue@, the target label must be directly associated with a \lstinline@for@, \lstinline@while@ or \lstinline@do@ statement;
1416for \lstinline@break@, the target label can also be associated with a \lstinline@switch@ statement.
1417Both \lstinline@break@ and \lstinline@continue@ with target labels are simply a \lstinline@goto@ restricted in the following ways:
1418\begin{itemize}
1419\item
1420They cannot be used to create a loop.
1421This means that only the looping construct can be used to create a loop.
1422This restriction is important since all situations that can result in repeated execution of statements in a program are clearly delineated.
1423\item
1424Since they always transfers out of containing control structures, they cannot be used to branch into a control structure.
1425\end{itemize}
1426The advantage of the labelled \lstinline@break@/\lstinline@continue@ is that it allows static multi-level exits without having to use the \lstinline@goto@ statement and ties control flow to the target control structure rather than an arbitrary point in a program.
1427Furthermore, the location of the label at the beginning of the target control structure informs the reader that complex control-flow is occurring in the body of the control structure.
1428With \lstinline@goto@, the label at the end of the control structure fails to convey this important clue early enough to the reader.
1429Finally, using an explicit target for the transfer instead of an implicit target allows new nested loop or switch constructs to be added or removed without affecting other constructs.
1430The implicit targets of the current \lstinline@break@ and \lstinline@continue@, i.e., the closest enclosing loop or \lstinline@switch@, change as certain constructs are added or removed.
1431
1432
1433\section{Switch Statement}
1434
1435C allows a number of questionable forms for the \lstinline@switch@ statement:
1436\begin{enumerate}
1437\item
1438By default, the end of a \lstinline@case@ clause\footnote{
1439In this section, the term \emph{case clause} refers to either a \lstinline@case@ or \lstinline@default@ clause.}
1440\emph{falls through} to the next \lstinline@case@ clause in the \lstinline@switch@ statement;
1441to exit a \lstinline@switch@ statement from a \lstinline@case@ clause requires explicitly terminating the clause with a transfer statement, most commonly \lstinline@break@, as in:
1442\begin{lstlisting}
1443switch ( i ) {
1444  case 1:
1445        ...
1446        // fall-through
1447  case 2:
1448        ...
1449        break;  // exit switch statement
1450}
1451\end{lstlisting}
1452The ability to fall-through to the next clause is a useful form of control flow, specifically when a sequence of case actions compound, as in:
1453\begin{lstlisting}
1454switch ( argc ) {
1455  case 3:
1456        // open output file
1457        // fall-through
1458  case 2:
1459        // open input file
1460        break;  // exit switch statement
1461  default:
1462        // usage message
1463}
1464\end{lstlisting}
1465In this example, case 2 is always done if case 3 is done.
1466This control flow is difficult to simulate with if statements or a \lstinline@switch@ statement without fall-through as code must be duplicated or placed in a separate routine.
1467C also uses fall-through to handle multiple case-values resulting in the same action, as in:
1468\begin{lstlisting}
1469switch ( i ) {
1470  case 1: case 3: case 5:       // odd values
1471        // same action
1472        break;
1473  case 2: case 4: case 6:       // even values
1474        // same action
1475        break;
1476}
1477\end{lstlisting}
1478However, this situation is handled in other languages without fall-through by allowing a list of case values.
1479While fall-through itself is not a problem, the problem occurs when fall-through is the \lstinline@default@, as this semantics is not intuitive to most programmers and is different from virtually all other programming languages with a \lstinline@switch@ statement.
1480Hence, \lstinline@default@ fall-through semantics results in a large number of programming errors as programmers often forget the \lstinline@break@ statement at the end of a \lstinline@case@ clause, resulting in inadvertent fall-through.
1481
1482\item
1483It is possible to place \lstinline@case@ clauses on statements nested \emph{within} the body of the \lstinline@switch@ statement, as in:
1484\begin{lstlisting}
1485switch ( i ) {
1486  case 0:
1487        if ( j < k ) {
1488                ...
1489          case 1:               // transfer into "if" statement
1490                if ( j < m ) {
1491                        ...
1492                  case 2:       // transfer into "if" statement
1493                        ...
1494                }
1495        }
1496  case 3:
1497        while ( j < 5 ) {
1498                ...
1499          case 4:               // transfer into "while" statement
1500                ...
1501        }
1502}
1503\end{lstlisting}
1504The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties.
1505The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it.
1506The technical problem results from the inability to ensure allocation and initialization of variables when blocks are not entered at the beginning.
1507Often transferring into a block can bypass variable declaration and/or its initialization, which results in subsequent errors.
1508There are virtually no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it.
1509Nevertheless, C does have an idiom where this capability is used, known as ``Duff's device''~\cite{Duff83}:
1510\begin{lstlisting}
1511register int n = (count + 7) / 8;
1512switch ( count % 8 ) {
1513case 0: do{ *to = *from++;
1514case 7:         *to = *from++;
1515case 6:         *to = *from++;
1516case 5:         *to = *from++;
1517case 4:         *to = *from++;
1518case 3:         *to = *from++;
1519case 2:         *to = *from++;
1520case 1:         *to = *from++;
1521                } while ( --n > 0 );
1522}
1523\end{lstlisting}
1524which unrolls a loop N times (N = 8 above) and uses the \lstinline@switch@ statement to deal with any iterations not a multiple of N.
1525While efficient, this sort of special purpose usage is questionable:
1526\begin{quote}
1527Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this
1528discovery.~\cite{Duff83}
1529\end{quote}
1530\item
1531It is possible to place the \lstinline@default@ clause anywhere in the list of labelled clauses for a \lstinline@switch@ statement, rather than only at the end.
1532Virtually all programming languages with a \lstinline@switch@ statement require the \lstinline@default@ clause to appear last in the case-clause list.
1533The logic for this semantics is that after checking all the \lstinline@case@ clauses without success, the \lstinline@default@ clause is selected;
1534hence, physically placing the \lstinline@default@ clause at the end of the \lstinline@case@ clause list matches with this semantics.
1535This physical placement can be compared to the physical placement of an \lstinline@else@ clause at the end of a series of connected \lstinline@if@/\lstinline@else@ statements.
1536
1537\item
1538It is possible to place unreachable code at the start of a \lstinline@switch@ statement, as in:
1539\begin{lstlisting}
1540switch ( x ) {
1541        int y = 1;                      // unreachable initialization
1542        x = 7;                          // unreachable code
1543  case 3: ...
1544        y = 3;
1545        ...
1546}
1547\end{lstlisting}
1548While the declaration of the local variable \lstinline@y@ is useful and its scope is across all \lstinline@case@ clauses, the initialization for such a variable is defined to never be executed because control always transfers over it.
1549Furthermore, any statements before the first \lstinline@case@ clause can only be executed if labelled and transfered to using a \lstinline@goto@, either from outside or inside of the \lstinline@switch@.
1550As mentioned, transfer into control structures should be forbidden.
1551Transfers from within the \lstinline@switch@ body using a \lstinline@goto@ are equally unpalatable.
1552\end{enumerate}
1553Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program:
1554\begin{itemize}
1555\item
1556the number of \lstinline@switch@ statements is small,
1557\item
1558most \lstinline@switch@ statements are well formed (i.e., no Duff's device),
1559\item
1560the \lstinline@default@ clause is usually written as the last case-clause,
1561\item
1562and there is only a medium amount of fall-through from one \lstinline@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.
1563\end{itemize}
1564These observations should help to put the effects of suggested changes into perspective.
1565% Figure 1 shows the grammar change that attempts to minimize the effect on existing C programs.
1566\begin{enumerate}
1567\item
1568Eliminating the \lstinline@default@ fall-through problem has the greatest potential for affecting existing code.
1569However, even if fall-through is removed, most \lstinline@switch@ statements would continue to work because of the explicit transfers already present at the end of each \lstinline@case@ clause, and the common placement of the \lstinline@default@ clause at the end of the case list.
1570In addition, the above grammar provides for the most common use of fall-through, i.e., a list of \lstinline@case@ clauses executing common code, e.g.:
1571\begin{lstlisting}
1572case 1:  case 2:  case 3: ...
1573\end{lstlisting}
1574Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments.
1575Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of \lstinline@switch@ statement, called \lstinline@choose@, with no fall-through semantics.
1576The \lstinline@choose@ statement is identical to the new \lstinline@switch@ statement, except there is no implicit fall-through between case-clauses and the \lstinline@break@ statement applies to the enclosing loop construct (as for the continue statement in a \lstinline@switch@ statement).
1577It is still possible to fall-through if a case-clause ends with the new keyword fallthru, e.g.:
1578\begin{lstlisting}
1579choose ( i ) {
1580        int i;
1581  case 3, 4:
1582        i = 3;
1583        fallthru;
1584  case 8, 10:
1585  default:
1586        j = 3;
1587}
1588\end{lstlisting}
1589The ability to fall-through is retained because it is a sufficient C-idiom that most C programmers simply expect it, and its absence might discourage these programmers from using the choose statement.
1590\item
1591Eliminating Duff's device is straightforward and only invalidates a small amount of very questionable code.
1592The solution is to allow \lstinline@case@ clauses to only appear at the same nesting level as the \lstinline@switch@ body, as is done in most other programming languages with \lstinline@switch@ statements.
1593\item
1594The issue of \lstinline@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 \lstinline@default@ clause may appear is locations other than at the end.
1595Therefore, no language change is made for this issue.
1596\item
1597Dealing with unreachable code at the start of a \lstinline@switch@ statement is solved by defining the declaration-list, including any associated initialization, at the start of a \lstinline@switch@ statement body to be executed before the transfer to the appropriate \lstinline@case@ clause.
1598This semantics is the same as for declarations at the start of a loop body, which are executed before each iteration of the loop body.
1599As well, this grammar does not allow statements to appear before the first \lstinline@case@ clause.
1600The change is compatible for declarations with initialization in this context because existing code cannot assume the initialization has occurred.
1601The change is incompatible for statements, but any existing code using it is highly questionable, as in:
1602\begin{lstlisting}
1603switch ( i ) {
1604        L: x = 5;               // questionable code
1605  case 0:
1606        ...
1607}
1608\end{lstlisting}
1609The statement after the \lstinline@switch@ can never be executed unless it is labelled.
1610If it is labelled, it must be transfered to from outside or inside the \lstinline@switch@ statement, neither of which is acceptable control flow.
1611\end{enumerate}
1612
1613
1614\section{Case Clause}
1615
1616C restricts the \lstinline@case@ clause of a \lstinline@switch@ statement to a single value.
1617For multiple \lstinline@case@ clauses associated with the same statement, it is necessary to have multiple \lstinline@case@ clauses rather than multiple values.
1618Requiring a \lstinline@case@ clause for each value does not seem to be in the spirit of brevity normally associated with C.
1619Therefore, the \lstinline@case@ clause is extended with a list of values, as in:
1620\begin{quote2}
1621\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
1622\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{C}}        \\
1623\begin{lstlisting}
1624switch ( i ) {
1625  case 1, 3, 5:
1626        ...
1627  case 2, 4, 6:
1628        ...
1629}
1630\end{lstlisting}
1631&
1632\begin{lstlisting}
1633switch ( i ) {
1634  case 1: case 3 : case 5:
1635        ...
1636  case 2: case 4 : case 6: /* even values */
1637        ...
1638}
1639\end{lstlisting}
1640&
1641\begin{lstlisting}
1642
1643// odd values
1644
1645// even values
1646
1647
1648\end{lstlisting}
1649\end{tabular}
1650\end{quote2}
1651In addition, two forms of subranges are allowed to specify case values: the GNU C form and a new \CFA form.
1652\begin{quote2}
1653\begin{tabular}{@{}l@{\hspace{30pt}}l@{\hspace{20pt}}l@{}}
1654\multicolumn{1}{c@{\hspace{30pt}}}{\textbf{\CFA}}       & \multicolumn{1}{c@{\hspace{20pt}}}{\textbf{GNU C}}    \\
1655\begin{lstlisting}
1656switch ( i ) {
1657  case 1~5
1658        ...
1659  case 10~15
1660        ...
1661}
1662\end{lstlisting}
1663&
1664\begin{lstlisting}
1665switch ( i )
1666  case 1 ... 5:
1667        ...
1668  case 10 ... 15:
1669        ...
1670}
1671\end{lstlisting}
1672&
1673\begin{lstlisting}
1674// 1, 2, 3, 4, 5
1675
1676// 10, 11, 12, 13, 14, 15
1677
1678
1679\end{lstlisting}
1680\end{tabular}
1681\end{quote2}
1682
1683
1684\section{Unnamed Structure Fields}
1685
1686C requires each field of a structure to have a name, except for a bit field associated with a basic type, e.g.:
1687\begin{lstlisting}
1688struct {
1689        int f1;                 // named field
1690        int f2 : 4;             // named field with bit field size
1691        int : 3;                // unnamed field for basic type with bit field size
1692        int ;                   // disallowed, unnamed field
1693        int *;                  // disallowed, unnamed field
1694        int (*)(int);   // disallowed, unnamed field
1695};
1696\end{lstlisting}
1697This requirement is relaxed by making the field name optional for all field declarations; therefore, all the field declarations in the example are allowed.
1698As for unnamed bit fields, an unnamed field is used for padding a structure to a particular size.
1699A list of unnamed fields is also supported, e.g.:
1700\begin{lstlisting}
1701struct {
1702        int , , ;               // 3 unnamed fields
1703}
1704\end{lstlisting}
1705
1706
1707\section{Exception Handling}
1708
1709Exception handling provides two mechanim: change of control flow from a raise to a handler, and commumication from the riase to the handler.
1710\begin{lstlisting}
1711exception void h( int i );
1712exception int h( int i, double d );
1713
1714void f(...) {
1715        ... throw h( 3 );
1716        ... i = resume h( 3, 5.1 );
1717}
1718
1719try {
1720        f(...);
1721} catch h( int w ) {
1722        // reset
1723} resume h( int p, double x ) {
1724        return 17;  // recover
1725} finally {
1726}
1727\end{lstlisting}
1728So 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.
1729The 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.
1730
1731
1732\section{Types}
1733
1734\subsection{Type Definitions}
1735
1736\CFA allows users to define new types using the keyword type.
1737
1738\begin{lstlisting}
1739// SensorValue is a distinct type and represented as an int
1740type SensorValue = int;
1741\end{lstlisting}
1742
1743A 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.
1744This means that users can define distinct function overloads for the new type (see Overloading for more information).
1745For example:
1746
1747\begin{lstlisting}
1748type SensorValue = int;
1749void printValue(int v) {...}
1750void printValue(SensorValue v) {...}
1751void process(int v) {...}
1752
1753SensorValue s = ...;
1754
1755printValue(s); // calls version with SensorValue argument
1756
1757printValue((int) s); // calls version with int argument
1758
1759process(s); // implicit conversion to int
1760\end{lstlisting}
1761
1762If SensorValue was defined with a typedef, then these two print functions would not have unique signatures.
1763This can be very useful to create a distinct type that has the same representation as another type.
1764
1765The compiler will assume it can safely convert from the old type to the new type, implicitly.
1766Users may override this and define a function that must be called to convert from one type to another.
1767
1768\begin{lstlisting}
1769type SensorValue = int;
1770// ()? is the overloaded conversion operator identifier
1771// This function converts an int to a SensorValue
1772SensorValue ()?(int val) {
1773        ...
1774}
1775void process(int v) {...}
1776
1777SensorValue s = ...;
1778process(s); // implicit call to conversion operator
1779\end{lstlisting}
1780
1781In many cases, it is not desired for the compiler to do this implicit conversion.
1782To avoid that, the user can use the explicit modifier on the conversion operator.
1783Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error.
1784
1785\begin{lstlisting}
1786type SensorValue = int;
1787
1788// conversion from int to SensorValue; must be explicit
1789explicit SensorValue ()?(int val) {
1790        ...
1791}
1792
1793void process(int v) {...}
1794
1795SensorValue s = ...;
1796process(s); // implicit cast to int: compile-time error
1797process((int) s); // explicit cast to int: calls conversion func
1798\end{lstlisting}
1799
1800The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to:
1801\begin{lstlisting}
1802type SensorValue = int;
1803explicit SensorValue ()?(int);
1804void process(int v) {...}
1805
1806SensorValue s = ...;
1807process(s); // compile-time error
1808process((int) s); // type is converted, no function is called
1809\end{lstlisting}
1810
1811
1812\subsection{Structures}
1813
1814Structures in \CFA are basically the same as structures in C.
1815A structure is defined with the same syntax as in C.
1816When referring to a structure in \CFA, users may omit the struct keyword.
1817\begin{lstlisting}
1818struct Point {
1819        double x;
1820        double y;
1821};
1822
1823Point p = {0.0, 0.0};
1824\end{lstlisting}
1825
1826\CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields.
1827Composition is achieved by embedding one type into another.
1828When 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.
1829Embedding types is achieved using anonymous members.
1830For example, using Point from above:
1831\begin{lstlisting}
1832void foo(Point p);
1833
1834struct ColoredPoint {
1835        Point; // anonymous member (no identifier)
1836        int Color;
1837};
1838...
1839        ColoredPoint cp = ...;
1840        cp.x = 10.3; // x from Point is accessed directly
1841        cp.color = 0x33aaff; // color is accessed normally
1842        foo(cp); // cp can be used directly as a Point
1843\end{lstlisting}
1844
1845
1846\subsection{Constructors and Destructors}
1847
1848\CFA supports C initialization of structures, but it also adds constructors for more advanced initialization.
1849Additionally, \CFA adds destructors that are called when a variable is de-allocated (variable goes out of scope or object is deleted).
1850These functions take a reference to the structure as a parameter (see
1851References for more information).
1852
1853\begin{figure}
1854\begin{lstlisting}
1855struct Widget {
1856        int id;
1857        float size;
1858        Parts *optionalParts;
1859};
1860
1861// ?{} is the constructor operator identifier
1862// The first argument is a reference to the type to initialize
1863// Subsequent arguments can be specified for initialization
1864
1865void ?{}(Widget &w) { // default constructor
1866        w.id = -1;
1867        w.size = 0.0;
1868        w.optionalParts = 0;
1869}
1870
1871// constructor with values (does not need to include all fields)
1872void ?{}(Widget &w, int id, float size) {
1873        w.id = id;
1874        w.size = size;
1875        w.optionalParts = 0;
1876}
1877
1878// ^? is the destructor operator identifier
1879void ^?(Widget &w) { // destructor
1880        w.id = 0;
1881        w.size = 0.0;
1882        if (w.optionalParts != 0) {
1883        // This is the only pointer to optionalParts, free it
1884        free(w.optionalParts);
1885        w.optionalParts = 0;
1886        }
1887}
1888
1889Widget baz; // reserve space only
1890Widget foo{}; // calls default constructor
1891Widget bar{23, 2.45}; // calls constructor with values
1892baz{24, 0.91}; // calls constructor with values
1893?{}(baz, 24, 0.91}; // explicit call to constructor
1894^bar; // explicit call to destructor
1895^?(bar); // explicit call to destructor
1896\end{lstlisting}
1897\caption{Constructors and Destructors}
1898\end{figure}
1899
1900
1901\begin{comment}
1902\section{References}
1903
1904\CFA supports reference types similar to rvalue references in \CC.
1905A reference is essentially an alias for a variable, allowing multiple names to refer to the same object.
1906A reference can be used as a safer alternative to a pointer, because it can be used to pass a variable by reference, but it must always reference an object.
1907It cannot be NULL, it must be assigned a value at initialization, and the object it references cannot change once it is set.
1908By introducing references in parameter types, users are given an easy way to pass a value by reference, without the need for NULL pointer checks.
1909In structures, a reference can replace a pointer to an object that should always have a valid value.
1910When a structure contains a reference, all of its constructors must initialize the reference and all instances of this structure must initialize it upon definition.
1911
1912The syntax for using references in \CFA is the same as \CC with the exception of reference initialization.
1913Use \lstinline@&@ to specify a reference, and access references just like regular objects, not like pointers (use dot notation to access fields).
1914When initializing a reference, \CFA uses a different syntax which differentiates reference initialization from assignment to a reference.
1915The \lstinline@&@ 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.
1916
1917\begin{figure}
1918\begin{lstlisting}
1919// parameter p is a reference to a Point
1920void movePointUp(Point &p) {
1921        p.y += 1.0; // Uses dot-notation to access fields
1922}
1923
1924Point p1 = ...;
1925ColoredPoint cp1 = ...;
1926movePoint(p1); // reference to p1 passed to movePoint
1927movePoint(cp1); // reference to cp1 passed to movePoint
1928
1929// a ListElement cannot be created without a valid list
1930
1931struct ListElement {
1932        int element;
1933        List &list; // a list element has a reference to the list
1934}
1935
1936// The constructor must initialize the reference
1937void ?{}(ListElement &le, int e, List &l) {
1938        le.element = e;
1939        &le.list = &l; // initialize the reference
1940}
1941
1942ListElement e1{88, numberList}; // uses constructor
1943ListElement e2; // compiler error: uninitialized reference
1944Listing 10: References
1945\end{lstlisting}
1946\end{figure}
1947\end{comment}
1948
1949
1950\section{Overloading}
1951
1952Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name.
1953In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C.
1954This may cause identical C and \CFA programs to behave differently.
1955The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used.
1956Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users.
1957Disadvantages 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.
1958\CFA allows overloading of functions, operators, variables, and even the constants 0 and 1.
1959
1960The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads.
1961The best valid interpretations are the valid interpretations that use the fewest unsafe conversions.
1962Of these, the best are those where the functions and objects involved are the least polymorphic.
1963Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions.
1964Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions.
1965If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous.
1966For details about type inference and overload resolution, please see the \CFA Language Specification.
1967\begin{lstlisting}
1968int foo(int a, int b) {
1969        float sum = 0.0;
1970        float special = 1.0;
1971        {
1972                int sum = 0;
1973                // both the float and int versions of sum are available
1974                float special = 4.0;
1975                // this inner special hides the outer version
1976                ...
1977        }
1978        ...
1979}
1980\end{lstlisting}
1981
1982
1983\subsection{Overloaded Constant}
1984
1985The constants 0 and 1 have special meaning.
1986In \CFA, as in C, all scalar types can be incremented and
1987decremented, which is defined in terms of adding or subtracting 1.
1988The operations \lstinline@&&@, \lstinline@||@, and \lstinline@!@ can be applied to any scalar arguments and are defined in terms of comparison against 0 (ex. \lstinline@(a && b)@ becomes \lstinline@(a != 0 && b != 0)@).
1989
1990In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any
1991arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a
1992special case.
1993However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their
1994functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their
1995polymorphic parameters, and user-defined pointer-like types may need a null value.
1996Defining special
1997constants for a user-defined type is more efficient than defining a conversion to the type from \lstinline@_Bool@.
1998
1999Why just 0 and 1? Why not other integers? No other integers have special status in C.
2000A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement.
2001Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed.
2002The complexity of such a feature doesn.t seem worth the gain.
2003
2004For example, to define the constants for a complex type, the programmer would define the following:
2005
2006\begin{lstlisting}
2007struct Complex {
2008        double real;
2009        double imaginary;
2010}
2011
2012const Complex 0 = {0, 0};
2013const Complex 1 = {1, 0};
2014...
2015
2016        Complex a = 0;
2017...
2018
2019        a++;
2020...
2021        if (a) { // same as if (a == 0)
2022...
2023}
2024\end{lstlisting}
2025
2026
2027\subsection{Variable Overloading}
2028
2029The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types.
2030Allowing 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.
2031For example, a developer may want to do the following:
2032\begin{lstlisting}
2033int pi = 3;
2034float pi = 3.14;
2035char pi = .p.;
2036\end{lstlisting}
2037
2038
2039\subsection{Function Overloading}
2040
2041Overloaded 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).
2042
2043The examples below give some basic intuition about how the resolution works.
2044\begin{lstlisting}
2045// Choose the one with less conversions
2046int doSomething(int value) {...} // option 1
2047int doSomething(short value) {...} // option 2
2048
2049int a, b = 4;
2050short c = 2;
2051
2052a = doSomething(b); // chooses option 1
2053a = doSomething(c); // chooses option 2
2054
2055// Choose the specialized version over the generic
2056
2057generic(type T)
2058T bar(T rhs, T lhs) {...} // option 3
2059float bar(float rhs, float lhs){...} // option 4
2060float a, b, c;
2061double d, e, f;
2062c = bar(a, b); // chooses option 4
2063
2064// specialization is preferred over unsafe conversions
2065
2066f = bar(d, e); // chooses option 5
2067\end{lstlisting}
2068
2069
2070\subsection{Operator Overloading}
2071
2072\CFA also allows operators to be overloaded, to simplify the use of user-defined types.
2073Overloading 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.
2074\CFA uses the following special identifiers to name overloaded operators:
2075
2076\begin{table}[hbt]
2077\hfil
2078\begin{tabular}[t]{ll}
2079%identifier & operation \\ \hline
2080\lstinline@?[?]@ & subscripting \impl{?[?]}\\
2081\lstinline@?()@ & function call \impl{?()}\\
2082\lstinline@?++@ & postfix increment \impl{?++}\\
2083\lstinline@?--@ & postfix decrement \impl{?--}\\
2084\lstinline@++?@ & prefix increment \impl{++?}\\
2085\lstinline@--?@ & prefix decrement \impl{--?}\\
2086\lstinline@*?@ & dereference \impl{*?}\\
2087\lstinline@+?@ & unary plus \impl{+?}\\
2088\lstinline@-?@ & arithmetic negation \impl{-?}\\
2089\lstinline@~?@ & bitwise negation \impl{~?}\\
2090\lstinline@!?@ & logical complement \impl{"!?}\\
2091\lstinline@?*?@ & multiplication \impl{?*?}\\
2092\lstinline@?/?@ & division \impl{?/?}\\
2093\end{tabular}\hfil
2094\begin{tabular}[t]{ll}
2095%identifier & operation \\ \hline
2096\lstinline@?%?@ & remainder \impl{?%?}\\
2097\lstinline@?+?@ & addition \impl{?+?}\\
2098\lstinline@?-?@ & subtraction \impl{?-?}\\
2099\lstinline@?<<?@ & left shift \impl{?<<?}\\
2100\lstinline@?>>?@ & right shift \impl{?>>?}\\
2101\lstinline@?<?@ & less than \impl{?<?}\\
2102\lstinline@?<=?@ & less than or equal \impl{?<=?}\\
2103\lstinline@?>=?@ & greater than or equal \impl{?>=?}\\
2104\lstinline@?>?@ & greater than \impl{?>?}\\
2105\lstinline@?==?@ & equality \impl{?==?}\\
2106\lstinline@?!=?@ & inequality \impl{?"!=?}\\
2107\lstinline@?&?@ & bitwise AND \impl{?&?}\\
2108\end{tabular}\hfil
2109\begin{tabular}[t]{ll}
2110%identifier & operation \\ \hline
2111\lstinline@?^?@ & exclusive OR \impl{?^?}\\
2112\lstinline@?|?@ & inclusive OR \impl{?"|?}\\
2113\lstinline@?=?@ & simple assignment \impl{?=?}\\
2114\lstinline@?*=?@ & multiplication assignment \impl{?*=?}\\
2115\lstinline@?/=?@ & division assignment \impl{?/=?}\\
2116\lstinline@?%=?@ & remainder assignment \impl{?%=?}\\
2117\lstinline@?+=?@ & addition assignment \impl{?+=?}\\
2118\lstinline@?-=?@ & subtraction assignment \impl{?-=?}\\
2119\lstinline@?<<=?@ & left-shift assignment \impl{?<<=?}\\
2120\lstinline@?>>=?@ & right-shift assignment \impl{?>>=?}\\
2121\lstinline@?&=?@ & bitwise AND assignment \impl{?&=?}\\
2122\lstinline@?^=?@ & exclusive OR assignment \impl{?^=?}\\
2123\lstinline@?|=?@ & inclusive OR assignment \impl{?"|=?}\\
2124\end{tabular}
2125\hfil
2126\caption{Operator Identifiers}
2127\label{opids}
2128\end{table}
2129
2130These identifiers are defined such that the question marks in the name identify the location of the operands.
2131These operands represent the parameters to the functions, and define how the operands are mapped to the function call.
2132For example, \lstinline@a + b@ becomes \lstinline@?+?(a, b)@.
2133
2134In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator.
2135These operators are called using the normal C syntax.
2136
2137\begin{lstlisting}
2138type Complex = struct { // define a Complex type
2139        double real;
2140        double imag;
2141}
2142
2143// Constructor with default values
2144
2145void ?{}(Complex &c, double real = 0.0, double imag = 0.0) {
2146        c.real = real;
2147        c.imag = imag;
2148}
2149
2150Complex ?+?(Complex lhs, Complex rhs) {
2151        Complex sum;
2152        sum.real = lhs.real + rhs.real;
2153        sum.imag = lhs.imag + rhs.imag;
2154        return sum;
2155}
2156
2157String ()?(const Complex c) {
2158        // use the string conversions for the structure members
2159        return (String)c.real + . + . + (String)c.imag + .i.;
2160}
2161...
2162
2163Complex a, b, c = {1.0}; // constructor for c w/ default imag
2164...
2165c = a + b;
2166print(.sum = . + c);
2167\end{lstlisting}
2168
2169
2170\section{Generics }
2171
2172\CFA supports parametric polymorphism to allow users to define generic functions and types.
2173Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types.
2174The type parameters can be restricted to satisfy a set of constraints.
2175This enables \CFA to build fully compiled generic functions and types, unlike other languages like \CC where templates are expanded or must be explicitly instantiated.
2176
2177
2178\subsection{Generic Functions}
2179
2180Generic functions in \CFA are similar to template functions in \CC, and will sometimes be expanded into specialized versions, just like in \CC.
2181The 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.
2182This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically).
2183Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated.
2184
2185A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this:
2186
2187\begin{lstlisting}
2188generic(type T)
2189void swap(T &a, T &b) {
2190        T tmp = a;
2191        a = b;
2192        b = a;
2193}
2194
2195int a, b;
2196swap(a, b);
2197
2198Point p1, p2;
2199swap(p1, p2);
2200\end{lstlisting}
2201
2202Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T.
2203This 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.
2204
2205
2206\subsection{Bounded Quantification}
2207
2208Some generic functions only work (or make sense) for any type that satisfies a given property.
2209For example, here is a function to pick the minimum of two values of some type.
2210\begin{lstlisting}
2211generic (type T | bool ?<?(T, T) )
2212
2213T min(T a, T b) {
2214        return a < b ? a : b;
2215}
2216\end{lstlisting}
2217
2218It 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.
2219The ordering function used here is the less than operator, <.
2220The syntax used to reference the operator is discussed in further detail in Operator Overloading.
2221In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)).
2222The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise.
2223
2224Bounds can also involve multiple types, and multiple requirements, as shown below:
2225\begin{lstlisting}
2226generic (type T, type U | { T foo(T, U); U bar(U); })
2227
2228T baz(T t, U u) {
2229        return foo(t, bar(u));
2230}
2231\end{lstlisting}
2232
2233
2234\subsection{Interfaces}
2235
2236Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type.
2237Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined.
2238Can 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.
2239The function signature doesn't say.
2240
2241Interfaces gather together a set of function signatures under a common name, which solves two problems.
2242First, an interface name can be used in type bounds instead of function signatures.
2243This avoids repetition when a bound is used in many functions.
2244Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand.
2245\begin{lstlisting}
2246generic (type T)
2247interface Orderable {
2248        bool ?<?(T, T);
2249};
2250
2251generic (type T | Orderable(T))
2252T min(T a, T b) {
2253        return a < b ? a : b;
2254}
2255\end{lstlisting}
2256
2257This definition of the interface Orderable makes the generic function min easier to read and understand.
2258Orderable can also be reused for other generic functions, max for example.
2259Interfaces can also build on top of other interfaces.
2260For example:
2261\begin{lstlisting}
2262generic (type T | Orderable(T)
2263interface FooBarable {
2264        int foo(T, T);
2265        int Bar(T, T);
2266};
2267\end{lstlisting}
2268
2269The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition.
2270A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time.
2271For 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.
2272
2273
2274\subsection{Generic Typedefs}
2275
2276Type synonyms can be defined generically using the typedef keyword together with a generic type annotation.
2277These can be used to abbreviate complicated type expressions, especially in generic code.
2278\begin{lstlisting}
2279// typedef the generic function pointers for later use
2280
2281generic(type T)
2282typedef int (*predicate)(T);
2283generic(type Captured, type T)
2284typedef void (*callback)(Captured, T);
2285
2286generic(type T)
2287void find(int length, T *array,
2288        predicate(T) p, callback(void *, T)f) {
2289        int i;
2290        for (i = 0; i < length; i++)
2291        if (p(array[i])) f(NULL, array[i]);
2292}
2293\end{lstlisting}
2294
2295
2296\subsection{Generic Types}
2297
2298Generic types are defined using the same mechanisms as those described above for generic functions.
2299This feature allows users to create types that have one or more fields that use generic parameters as types, similar to a template classes in \CC.
2300For 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.
2301In C, something like this would have to be done using void pointers and unsafe casting.
2302As 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.
2303This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds.
2304
2305The syntax for defining a generic type looks very similar to that of a generic function.
2306Generic types support bounds and interfaces, using the same syntax as generic functions.
2307\begin{lstlisting}
2308generic (type T)
2309struct LinkedListElem {
2310        T elem;
2311        LinkedListElem(T) *next;
2312};
2313
2314LinkedListElem *++?(LinkedListElem **elem) {
2315        return *elem = elem->next;
2316}
2317
2318generic (type T)
2319struct LinkedList {
2320        LinkedListElem(T) *head;
2321        unsigned int size;
2322}
2323
2324generic (type T | bool ?==?(T, T))
2325bool contains(LinkedList(T) *list, T elem) {
2326        for(LinkedListElem *iter = list->head; iter != 0; ++iter) {
2327        if (iter->elem == elem) return true;
2328        }
2329        return false;
2330}
2331\end{lstlisting}
2332
2333
2334\section{Safety}
2335
2336Safety, along with productivity, is a key goal of Do.
2337This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code.
2338
2339
2340\subsection{Exceptions}
2341
2342\CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code.
2343In C, developers can use error codes and special return values to report to a caller that an error occurred in a function.
2344The major problem with error codes is that they can be easily ignored by the caller.
2345Failure 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.
2346An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state.
2347
2348Exceptions in \CFA allow a different type of control flow.
2349Throwing 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.
2350The exception is immediately re-thrown from the parent block unless it is caught as described below.
2351\CFA uses keywords similar to \CC for exception handling.
2352An exception is thrown using a throw statement, which accepts one argument.
2353
2354\begin{lstlisting}
2355        ...
2356
2357        throw 13;
2358
2359        ...
2360\end{lstlisting}
2361
2362An exception can be caught using a catch statement, which specifies the type of the exception it can catch.
2363A catch is specified immediately after a guarded block to signify that it can catch an exception from that block.
2364A guarded block is specified using the try keyword, followed by a block of code inside of curly braces.
2365
2366\begin{lstlisting}
2367        ...
2368
2369        try {
2370        throw 13;
2371        }
2372        catch(int e) {
2373        printf(.caught an exception: %d\n., e);
2374        }
2375\end{lstlisting}
2376
2377
2378\subsection{Memory Management}
2379
2380
2381\subsubsection{Manual Memory Management}
2382
2383Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
2384First, malloc breaks type safety because it returns a pointer to void.
2385There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
2386This problem is solved with a type-safe malloc.
2387Do.s type-safe malloc does not take any arguments for size.
2388Instead, it infers the type based on the return value, and then allocates space for the inferred type.
2389
2390\begin{lstlisting}
2391float *f = malloc(); // allocates the size of a float
2392
2393struct S {
2394        int i, j, k;
2395};
2396
2397struct S *s = malloc(); // allocates the size of a struct S
2398\end{lstlisting}
2399
2400In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
2401For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
2402
2403\begin{lstlisting}
2404type Complex = struct {
2405        float real;
2406        float imag;
2407};
2408
2409// default constructor
2410
2411void ?{}(Complex &c) {
2412        c.real = 0.0;
2413        c.imag = 0.0;
2414}
2415
2416
2417
2418// 2 parameter constructor
2419
2420void ?{}(Complex &c, float real, float imag) {
2421        c.real = real;
2422        c.imag = imag;
2423}
2424
2425
2426int main() {
2427        Complex c1; // No constructor is called
2428        Complex c2{}; // Default constructor called
2429        Complex c3{1.0, -1.0}; // 2 parameter constructor is called
2430
2431        Complex *p1 = malloc(); // allocate
2432        Complex *p2 = new(); // allocate + default constructor
2433        Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
2434}
2435
2436\end{lstlisting}
2437
2438
2439\subsubsection{Automatic Memory Management}
2440
2441\CFA may also support automatic memory management to further improve safety.
2442If 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.
2443This feature requires further investigation.
2444\CFA will not have a garbage collector, but might use some kind of region-based memory management.
2445
2446
2447\subsection{Unsafe C Constructs}
2448
2449C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
2450Some of these practices however are often error-prone and difficult to read and maintain.
2451Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
2452If 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.
2453This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
2454
2455The 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.
2456Once the full set is decided, the rules will be listed here.
2457
2458
2459\section{I/O Library}
2460\label{s:IOLibrary}
2461
2462The goal for \CFA I/O is to make I/O as simple as possible for the general case, while fully supporting polmorphism and user defined types in a consistent way.
2463The general case is printing out a sequence of variables separated by whitespace.
2464\begin{lstlisting}
2465int x = 0, y = 1, z = 2;
2466sout | x | y | z | endl;
2467
2468cout << x << " " << y << " " << z << endl;
2469\end{lstlisting}
2470The \CC form takes almost twice as many characters.
2471
2472The logical-or operator is used because it is the lowest priority overloadable operator, other than assignment.
2473Therefore, most output expressions do not require parenthesis.
2474\begin{lstlisting}
2475int x = 0, y = 1, z = 2;
2476sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
2477
2478cout << x * 3 << y + 1 << (z << 2) << (x == y) << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
2479\end{lstlisting}
2480
2481Finally, the logical-or operator has a link with the Shell pipe-operator for moving data, although data flows in the opposite direction.
2482
2483\begin{figure}
2484\begin{lstlisting}[mathescape=off]
2485#include <fstream>
2486
2487int main() {
2488        char c;
2489        short int si;
2490        unsigned short int usi;
2491        int i;
2492        unsigned int ui;
2493        long int li;
2494        unsigned long int uli;
2495        long long int lli;
2496        unsigned long long int ulli;
2497        float f;
2498        double d;
2499        long double ld;
2500        float _Complex fc;
2501        double _Complex dc;
2502        long double _Complex ldc;
2503        char s1[10], s2[10];
2504
2505        ifstream in;
2506        open( &in, "read.data", "r" );
2507
2508        &in | &c
2509                | &si | &usi | &i | &ui | &li | &uli | &lli | &ulli
2510                | &f | &d | &ld
2511                | &fc | &dc | &ldc
2512                | str( s1 ) | str( s2, 10 );
2513
2514        sout | c | ' ' | endl
2515                 | si | usi | i | ui | li | uli | lli | ulli | endl
2516                 | f | d | ld | endl
2517                 | f | "" | d | "" | ld | endl;
2518
2519        sepSet( sout, ", $" );
2520        sout | fc | dc | ldc | endl
2521                 | sepOn | s1 | sepOff | s2 | endl
2522                 | s1 | "" | s2 | endl;
2523}
2524
2525$ cat read.data
2526A 1 2 3 4 5 6 7 8 1.1 1.2 1.3 1.1+2.3 1.1-2.3 1.1-2.3 abc xyz
2527$ a.out
2528A
25291 2 3 4 5 6 7 8
25301.1 1.2 1.3
25311.11.21.3
25321.1+2.3i, $1.1-2.3i, $1.1-2.3i
2533, $abcxyz
2534abcxyz
2535\end{lstlisting}
2536\end{figure}
2537
2538
2539\section{Standard Library}
2540\label{s:StandardLibrary}
2541
2542The goal of the \CFA standard-library is to wrap many of the existing C library-routines that are explicitly polymorphic into implicitly polymorphic versions.
2543
2544
2545\subsection{malloc}
2546
2547\begin{lstlisting}
2548forall( otype T ) T * malloc( void );
2549forall( otype T ) T * malloc( char fill );
2550forall( otype T ) T * malloc( T * ptr, size_t size );
2551forall( otype T ) T * malloc( T * ptr, size_t size, unsigned char fill );
2552forall( otype T ) T * calloc( size_t size );
2553forall( otype T ) T * realloc( T * ptr, size_t size );
2554forall( otype T ) T * realloc( T * ptr, size_t size, unsigned char fill );
2555
2556forall( otype T ) T * aligned_alloc( size_t alignment );
2557forall( otype T ) T * memalign( size_t alignment );             // deprecated
2558forall( otype T ) int posix_memalign( T ** ptr, size_t alignment );
2559
2560forall( otype T ) T * memset( T * ptr, unsigned char fill ); // use default value '\0' for fill
2561forall( otype T ) T * memset( T * ptr );                                // remove when default value available
2562\end{lstlisting}
2563
2564
2565\subsection{ato/strto}
2566
2567\begin{lstlisting}
2568int ato( const char * ptr );
2569unsigned int ato( const char * ptr );
2570long int ato( const char * ptr );
2571unsigned long int ato( const char * ptr );
2572long long int ato( const char * ptr );
2573unsigned long long int ato( const char * ptr );
2574float ato( const char * ptr );
2575double ato( const char * ptr );
2576long double ato( const char * ptr );
2577float _Complex ato( const char * ptr );
2578double _Complex ato( const char * ptr );
2579long double _Complex ato( const char * ptr );
2580
2581int strto( const char * sptr, char ** eptr, int base );
2582unsigned int strto( const char * sptr, char ** eptr, int base );
2583long int strto( const char * sptr, char ** eptr, int base );
2584unsigned long int strto( const char * sptr, char ** eptr, int base );
2585long long int strto( const char * sptr, char ** eptr, int base );
2586unsigned long long int strto( const char * sptr, char ** eptr, int base );
2587float strto( const char * sptr, char ** eptr );
2588double strto( const char * sptr, char ** eptr );
2589long double strto( const char * sptr, char ** eptr );
2590float _Complex strto( const char * sptr, char ** eptr );
2591double _Complex strto( const char * sptr, char ** eptr );
2592long double _Complex strto( const char * sptr, char ** eptr );
2593\end{lstlisting}
2594
2595
2596\subsection{bsearch/qsort}
2597
2598\begin{lstlisting}
2599forall( otype T | { int ?<?( T, T ); } )
2600T * bsearch( const T key, const T * arr, size_t dimension );
2601
2602forall( otype T | { int ?<?( T, T ); } )
2603void qsort( const T * arr, size_t dimension );
2604\end{lstlisting}
2605
2606
2607\subsection{abs}
2608
2609\begin{lstlisting}
2610char abs( char );
2611extern "C" {
2612int abs( int );         // use default C routine for int
2613} // extern
2614long int abs( long int );
2615long long int abs( long long int );
2616float abs( float );
2617double abs( double );
2618long double abs( long double );
2619float _Complex abs( float _Complex );
2620double _Complex abs( double _Complex );
2621long double _Complex abs( long double _Complex );
2622\end{lstlisting}
2623
2624
2625\subsection{random}
2626
2627\begin{lstlisting}
2628void randseed( long int s );
2629char random();
2630int random();
2631unsigned int random();
2632long int random();
2633unsigned long int random();
2634float random();
2635double random();
2636float _Complex random();
2637double _Complex random();
2638long double _Complex random();
2639\end{lstlisting}
2640
2641
2642\subsection{min/max/swap}
2643
2644\begin{lstlisting}
2645forall( otype T | { int ?<?( T, T ); } )
2646T min( const T t1, const T t2 );
2647
2648forall( otype T | { int ?>?( T, T ); } )
2649T max( const T t1, const T t2 );
2650
2651forall( otype T )
2652void swap( T * t1, T * t2 );
2653\end{lstlisting}
2654
2655
2656\section{Concurrency}
2657
2658Today's processors for nearly all use cases, ranging from embedded systems to large cloud computing servers, are composed of multiple cores, often heterogeneous.
2659As machines grow in complexity, it becomes more difficult for a program to make the most use of the hardware available.
2660\CFA includes built-in concurrency features to enable high performance and improve programmer productivity on these multi-/many-core machines.
2661
2662Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads.
2663The model integrates concurrency features into the language by making the structure type the core unit of concurrency.
2664All communication occurs through method calls, where data is sent via method arguments, and received via the return value.
2665This enables a very familiar interface to all programmers, even those with no parallel programming experience.
2666It also allows the compiler to do static type checking of all communication, a very important safety feature.
2667This controlled communication with type safety has some similarities with channels in Go, and can actually implement
2668channels exactly, as well as create additional communication patterns that channels cannot.
2669Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads.
2670
2671Three new keywords are added to support these features:
2672
2673monitor creates a structure with implicit locking when accessing fields
2674
2675mutex implies use of a monitor requiring the implicit locking
2676
2677task creates a type with implicit locking, separate stack, and a thread
2678
2679\subsection{Monitors}
2680
2681A monitor is a structure in \CFA which includes implicit locking of its fields.
2682Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion.
2683An example of the definition of a monitor is shown here:
2684\begin{lstlisting}
2685type Account = monitor {
2686        const unsigned long number; // account number
2687        float balance; // account balance
2688};
2689\end{lstlisting}
2690
2691Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor;
2692it is always passed by reference.
2693Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter.
2694When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body.
2695This means that a function requiring mutual exclusion could block if the lock is already held by another thread.
2696Blocking 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.
2697If multiple mutex parameters are specified, they will be locked in parameter order (i.e. first parameter is locked first) and unlocked in the
2698reverse order.
2699\begin{lstlisting}
2700// This function accesses a constant field, it does not require
2701// mutual exclusion
2702
2703export unsigned long getAccountNumber(Account &a) {
2704        return a.number;
2705}
2706
2707// This function accesses and modifies a shared field; it
2708// requires mutual exclusion
2709
2710export float withdrawal(mutex Account &a, float amount) {
2711        a.balance -= amount;
2712        return a.balance;
2713}
2714\end{lstlisting}
2715
2716Often, one function using a monitor will call another function using that same monitor.
2717If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function.
2718This 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.
2719It will still be unlocked the same number of times.
2720An example of this situation is shown below:
2721
2722\begin{lstlisting}
2723// deleting a job from a worker requires mutual exclusion
2724
2725void deleteJob(mutex Worker &w, Job &j) {
2726        ...
2727}
2728
2729// transferring requires mutual exclusion and calls deleteJob
2730
2731void transferJob(mutex Worker &from, Worker &to) {
2732        ...
2733        deleteJob(j);
2734        ...
2735}
2736\end{lstlisting}
2737
2738
2739\subsection{Tasks}
2740
2741\CFA also provides a simple mechanism for creating and utilizing user level threads.
2742A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control.
2743Similar to a monitor, a task is defined like a structure:
2744\begin{lstlisting}
2745type Adder = task {
2746        int *row;
2747        int size;
2748        int &subtotal;
2749}
2750\end{lstlisting}
2751
2752A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
2753A 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).
2754After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
2755All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
2756Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
2757(Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
2758\begin{lstlisting}
2759void ?{}(Adder &a, int r[], int s, int &st) { // constructor
2760        a.row = r;
2761        a.size = s;
2762        a.subtotal = st;
2763}
2764
2765// implicitly spawn thread and begin execution here
2766
2767void ?()(Adder &a) {
2768        int c;
2769        subtotal = 0;
2770        for (c=0; c<a.size; ++c) {
2771        subtotal += row[c];
2772        }
2773}
2774
2775int main() {
2776        const int rows = 100, cols = 1000000;
2777        int matrix[rows][cols];
2778        int subtotals[rows];
2779        int total = 0;
2780        int r;
2781
2782        { // create a new scope here for our adders
2783        Adder adders[rows];
2784        // read in the matrix
2785        ...
2786        for (r=0; r<rows; ++r) {
2787        // tasks are initialized on this thread
2788        Adders[r] = {matrix[r], cols, subtotals[r]};
2789        Adders[r](); // spawn thread and begin execution
2790        }
2791        } // adders go out of scope; block here until they all finish
2792        total += subtotals[r];
2793        printf(.total is %d\n., total);
2794}
2795\end{lstlisting}
2796
2797
2798\subsection{Cooperative Scheduling}
2799
2800Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
2801In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
2802Places 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.
2803This 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.
2804For example, the code below defines a monitor that maintains a generic list.
2805When 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.
2806Similarly, 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.
2807
2808\begin{lstlisting}
2809// type T is used as a generic type for all definitions inside
2810// the curly brackets
2811
2812generic(type T) {
2813        type Channel = monitor {
2814        List(T) list; // list is a simple generic list type
2815        };
2816
2817        T pop(mutex &Channel(T) ch) {
2818        if (ch.list.empty()) {
2819        // yield until push is called for this channel
2820        yield(push);
2821        }
2822        return ch.list.pop();
2823        }
2824
2825        void push(mutex &Channel(T)ch, T val) {
2826        if (ch.list.full()) {
2827        // yield until pop is called for this channel
2828        yield(pop);
2829        }
2830        ch.list.push(val);
2831        }
2832}
2833\end{lstlisting}
2834
2835A task can also yield indefinitely by calling yield with no arguments.
2836This will tell the scheduler to yield this task until it is resumed by some other task.
2837A task can resume another task by using its functional call operator.
2838The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
2839
2840\begin{lstlisting}
2841type Ping = task {
2842        Pong *partner;
2843};
2844
2845void ?{}(Ping &p, Pong *partner = 0) {
2846        p.partner = partner;
2847}
2848
2849void ?()(Ping &p) {
2850        for(;;) { // loop forever
2851        printf(.ping\n.);
2852        partner(); // resumes the partner task
2853        yield(); // yields this task
2854        }
2855}
2856
2857type Pong = task {
2858        Ping *partner;
2859};
2860
2861void ?{}(Pong &p, Ping *partner = 0) {
2862        p.partner = partner;
2863}
2864
2865void ?()(Pong &p) {
2866        for(;;) { // loop forever
2867        yield(); // yields this task
2868        printf(.pong/n.);
2869        partner(); // resumes the partner task
2870        }
2871}
2872
2873void main() {
2874        Ping ping; // allocate ping
2875        Pong pong{ping}; // allocate, initialize, and start pong
2876        Ping{pong}; // initialize and start ping
2877}
2878\end{lstlisting}
2879
2880The same functionality can be accomplished by providing functions to be called by the partner task.
2881\begin{lstlisting}
2882type Pingpong = task {
2883        String msg;
2884        Pingpong *partner;
2885};
2886
2887void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
2888        p.msg = msg;
2889        p.partner = partner;
2890}
2891
2892void ?()(Pingpong &p) {
2893        for(;;) {
2894        yield(go);
2895        }
2896}
2897
2898void go(Pingpong &p) {
2899        print(.%(p.msg)\n.);
2900        go(p.partner);
2901}
2902
2903void main() {
2904        Pingpong ping = {.ping.};
2905        Pingpong pong = {.pong., ping};
2906        ping.partner = pong;
2907        go(ping);
2908}
2909\end{lstlisting}
2910
2911
2912\section{Modules and Packages }
2913
2914\begin{comment}
2915High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed.
2916\CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time.
2917
2918There are two levels of encapsulation in \CFA, module and package.
2919A module is a logical grouping of functionality that can be easily pulled into another project, much like a module in Python or a package in Go.
2920A module forms a namespace to limit the visibility and prevent naming conflicts of variables.
2921Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed.
2922
2923A package is a physical grouping of one or more modules that is used for code distribution and version management.
2924Package is also the level of granularity at which dependences are managed.
2925A package is similar to the Crate in Rust.
2926
2927
2928\subsection{No Declarations, No Header Files}
2929
2930In C and \CC, it is necessary to declare or define every global variable, global function, and type before it is used in each file.
2931Header files and a preprocessor are normally used to avoid repeating code.
2932Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work.
2933Instead of following this model, the \CFA tools can extract all of the same information from the code automatically.
2934This 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.
2935In 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.
2936This seems like a minor change, but according to (Pike, Go at Google: Language Design in the Service of Software Engineering), this simple change can cause massive reductions in compile time.
2937
2938In \CFA, multiple definitions are not necessary.
2939Within a module, all of the module's global definitions are visible throughout the module.
2940For example, the following code compiles, even though isOdd was not declared before being called:
2941\begin{lstlisting}
2942bool isEven(unsigned int x) {
2943        if (x == 0) return true;
2944        else return !isOdd(x);
2945}
2946
2947bool isOdd(unsigned int x) {
2948        if (x == 1) return true;
2949        else return !isEven(x - 2);
2950}
2951\end{lstlisting}
2952
2953Header files in C are used to expose the declarations from a library, so that they can be used externally.
2954With \CFA, this functionality is replaced with module exports, discussed below.
2955When 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.
2956
2957In 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).
2958
2959
2960\subsection{Modules}
2961
2962A 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.
2963These modules can then be easily shared and reused in multiple projects.
2964As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces.
2965
2966\CFA adds the following keywords to express the module systems: module, export, import, as.
2967
2968
2969\subsubsection{Module Declaration}
2970
2971The syntax to declare a module is module moduleName;.
2972
2973The module declaration must be at the beginning of a file, and each file can only belong to one module.
2974If there is no module declaration at the beginning of a file, the file belongs to the global module.
2975A module can span several files.
2976By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation.
2977
2978The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship.
2979For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container.
2980
2981Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface.
2982A method, a global variable or a type can be declared as a module interface.
2983Types defined in a module and referenced by an exported function or a variable must be exported, too.
2984
2985The following code is a simple module declaration example.
2986\begin{lstlisting}
2987module M;
2988
2989//visible outside module M
2990
2991export int f(int i) { return i + 1; }
2992export double aCounter;
2993
2994//not visible outside module M
2995
2996int g(int i) { return i - 1; }
2997
2998double bCounter;
2999\end{lstlisting}
3000
3001export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module.
3002
3003
3004\subsubsection{Module Import}
3005
3006The syntax to import a module is import moduleName; or import moduleName as anotherName;.
3007One package cannot be imported with both of the two types of syntax in one file.
3008A package imported in one file will only be visible in this file.
3009For example, two files, A and B belong to the same module.
3010If file A imports another module, M, the exported names in M are not visible in file B.
3011
3012All of the exported names are visible in the file that imports the module.
3013The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo).
3014If 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(...);).
3015The 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.
3016Conflicts in namespaces will be reported by the compiler.
3017The second method can be used to solve conflicting name problems.
3018The following code snippets show the two situations.
3019
3020\begin{lstlisting}
3021module util/counter;
3022export int f(int i) { return i+1; }
3023
3024import util/counter;
3025
3026int main() {
3027        return counter.f(200); // f() from the package counter
3028}
3029
3030import util/counter as ct;
3031int main() {
3032        return ct.f(200); // f() from the package counter
3033}
3034\end{lstlisting}
3035
3036
3037Additionally, 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.
3038
3039\begin{lstlisting}
3040module M1;
3041export int f(int i) { return i+1;} // visible outside
3042
3043int g(int i) { return i-1;} // not visible outside
3044
3045module M2;
3046int f(int i) { return i * 2; } // not visible outside
3047export int g(int g) { return i / 2; } // visible outside
3048
3049import M1 as .;
3050
3051import M2 as .;
3052
3053
3054int main() {
3055        return f(3) + g(4); //f() from M1 and g() from M2;
3056}
3057\end{lstlisting}
3058
3059
3060\subsubsection{Sub-Module and Module Aggregation}
3061
3062Several modules can be organized in a parent module and sub-modules relationship.
3063The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship.
3064For example, std/vector and std/io are sub-modules of module std.
3065The 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
3066not implicitly exported in the parent module.
3067
3068Aggregation is a mechanism to support components and simplified importing.
3069The mechanism is not based on naming but based on manual declaration.
3070For example, the following is the aggregated sequence module.
3071The export {...} is syntactic sugar for many lines of export module aModule;.
3072If an aggregated module is imported, all the included modules in the aggregation are imported.
3073
3074\begin{lstlisting}
3075module std/sequence;
3076
3077export {
3078        module std/vector;
3079        module std/list;
3080        module std/array;
3081        module std/deque;
3082        module std/forward_list;
3083        module std/queue;
3084        module std/stack;
3085};
3086\end{lstlisting}
3087
3088After importing the aggregated module, each individual name is still contained in the original name space.
3089For 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.
3090
3091
3092\subsubsection{Import from Repository}
3093
3094When 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).
3095The tools also support retrieving modules of a package from external repositories.
3096See Listing 40: Package directory structure
3097
3098
3099\subsubsection{Package Import}
3100
3101Because 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.
3102In 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;
3103or 2) Adding the package dependence into the current project's Do.prj.
3104More details about locating a module in a package are explained in the next section.
3105
3106
3107\subsubsection{Package Versioning}
3108
3109A package must have a version number.
3110The version number is a string.
3111For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3112By convention, a package is stored in a directory named packageName-packageVersion.
3113For example, the util package with version 1.1 is stored in a directory named util-1.1.
3114
3115The project description file can optionally specify the version of the package used in the current project.
3116If 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.
3117The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3118
3119
3120\subsection{Module and Package Organization}
3121
3122\CFA has two level of encapsulations, module and package.
3123This section explains the object model of modules, packages and other language concepts.
3124It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3125
3126
3127\subsubsection{Object Model}
3128
3129There are several concepts in Do.
3130\begin{itemize}
3131\item
3132File: a \CFA source file
3133\item
3134Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3135\item
3136Package: a container to organize modules for distribution; It has attributes like name, author,
3137version, dependences, etc.
3138\item
3139Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3140\end{itemize}
3141
3142The following rules summarize the object model of all the above concepts:
3143\begin{itemize}
3144\item
3145A module contains one or more files
3146\begin{itemize}
3147\item
3148One file can only belong to one module
3149\item
3150A module has its name and interfaces exported
3151\item
3152A file without a module declaration at the beginning belongs to the global module
3153\item
3154\end{itemize}
3155
3156\item
3157A package contains one or more modules
3158\begin{itemize}
3159\item
3160A package has additional meta info described in Do.prj file
3161\item
3162A package may be dependent on other packages.
3163\end{itemize}
3164
3165\item
3166A project contains one or more modules in its source code
3167\begin{itemize}
3168\item
3169A project has additional meta info described in Do.prj file
3170\item
3171A project may be dependent on other packages
3172\item
3173A project can be transformed into a package for distribution
3174\item
3175A project can generate one or more executable binaries
3176\end{itemize}
3177\end{itemize}
3178
3179
3180\subsubsection{Module File Organization}
3181
3182The rules of this section are the conventions to organize module files in one package.
3183
3184The file location of a module in a package must match the module/submodule naming hierarchy.
3185The names separated by slash "/" must match the directory levels.
3186If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3187The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3188
3189Here is an example of a package, util.
3190\begin{lstlisting}
3191+ util
3192Do.prj #package description file
3193        heap.do #Case 1: module heap;
3194        list.do #Case 1: mdoule list;
3195        ring.do #Case 1: module ring;
3196        + string #Case 2
3197        impl1.do #module string;
3198        + std
3199        vector.do
3200        list.do
3201        + array #Case 3
3202        array1.do #module std/array;
3203        array2.do #module std/array;
3204        sequence.do #Case 4, module std/sequence;
3205        test.do #Case 5
3206\end{lstlisting}
3207
3208\begin{itemize}
3209\item
3210Case 1: Each individual file implements a module
3211\item
3212Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3213\item
3214Case 3: Put the implementation of a module under the sub-directory; There are several files to
3215implement one module
3216\item
3217Case 4: One file to express one aggregation
3218\item
3219Case 5: The file does not belong to any module; It is used for testing purpose
3220\end{itemize}
3221
3222The example only uses source code, ".do" files, to show the module file organization.
3223Other module packaging formats, like binary, must also follow the same rules.
3224
3225
3226\subsection{Module File Format}
3227
3228\CFA supports different types of module file formats.
3229
3230\begin{itemize}
3231\item
3232Pure source code format: The files should be organized following the previous section's definition.
3233\item
3234IR format (TBD): The \CFA compiler IR format, similar to the source code format
3235\item
3236Binary format, including ".a" static library or ".so" dynamic linkage library
3237\begin{itemize}
3238\item
3239The file's name must match the right level's module name defined in the previous section
3240\item
3241E.g. "util.so" includes all modules for the package util.
3242\item
3243E.g. "string.so" under the package directory to include files belonging to "module string;"
3244\end{itemize}
3245\item.
3246Archive format
3247\begin{itemize}
3248\item
3249The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3250\item
3251E.g. "util.dar" is the whole package for util package including the package direction file
3252\end{itemize}
3253\item
3254Hybrid format
3255\begin{itemize}
3256\item
3257A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3258\item
3259The only limitation is that the names of the files must match the module location names defined in previous section
3260\end{itemize}
3261\end{itemize}
3262Package and Module Locating and the \CFA Language Tooling documentation for more details.
3263
3264
3265\subsection{Packages}
3266
3267A package is synonymous with a library in other languages.
3268The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management.
3269A package is a physical grouping of one or more modules in a directory (an archive file for a directory).
3270The 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.
3271
3272
3273\subsubsection{Package Definition}
3274
3275A package is defined by putting a project description file, Do.prj, with one or more modules into a directory.
3276This project description file contains the package's meta data, including package name, author, version, dependences, etc.
3277It should be in the root of the package directory.
3278
3279The modules in the package could be either source code, or compiled binary format.
3280The location of the module files should follow the module name's path.
3281
3282Here is a simple example of the directory structure of a package, core.
3283It contains a module std and several sub-modules under std.
3284\begin{lstlisting}
3285+ core
3286        Do.prj
3287        + std
3288        + io
3289        file.do # module std/io/file;
3290        network.do #module std/io/network;
3291        + container
3292        vector.do #module std/container/vector;
3293        list.do #module std/container/list;
3294\end{lstlisting}
3295
3296
3297\subsubsection{Package Import}
3298
3299Because 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.
3300In 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.
3301More details about locating a module in a package are explained in the next section.
3302
3303
3304\subsubsection{Package Versioning}
3305
3306A package must have a version number.
3307The version number is a string.
3308For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3309By convention, a package is stored in a directory named packageName-packageVersion.
3310For example, the util package with version 1.1 is stored in a directory named util-1.1.
3311
3312The project description file can optionally specify the version of the package used in the current project.
3313If 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.
3314The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3315
3316
3317\subsection{Module and Package Organization}
3318
3319\CFA has two level of encapsulations, module and package.
3320This section explains the object model of modules, packages and other language concepts.
3321It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3322
3323
3324\subsubsection{Object Model}
3325
3326There are several concepts in Do.
3327\begin{itemize}
3328\item
3329File: a \CFA source file
3330\item
3331Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3332\item
3333Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc.
3334\item
3335Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3336\end{itemize}
3337
3338The following rules summarize the object model of all the above concepts:
3339\begin{itemize}
3340\item
3341A module contains one or more files
3342\begin{itemize}
3343\item
3344One file can only belong to one module
3345\item
3346A module has its name and interfaces exported
3347\item
3348A file without a module declaration at the beginning belongs to the global module
3349\end{itemize}
3350\item
3351A package contains one or more modules
3352\begin{itemize}
3353\item
3354A package has additional meta info described in Do.prj file
3355\item
3356A package may be dependent on other packages.
3357\end{itemize}
3358\item
3359A project contains one or more modules in its source code
3360\begin{itemize}
3361\item
3362A project has additional meta info described in Do.prj file
3363\item
3364A project may be dependent on other packages
3365\item
3366A project can be transformed into a package for distribution
3367\item
3368A project can generate one or more executable binaries
3369\end{itemize}
3370\end{itemize}
3371
3372
3373\subsubsection{Module File Organization}
3374
3375The rules of this section are the conventions to organize module files in one package.
3376
3377The file location of a module in a package must match the module/submodule naming hierarchy.
3378The names separated by slash "/" must match the directory levels.
3379If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3380The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3381
3382Here is an example of a package, util.
3383\begin{lstlisting}
3384+ util
3385        Do.prj #package description file
3386        heap.do #Case 1: module heap;
3387        list.do #Case 1: mdoule list;
3388        ring.do #Case 1: module ring;
3389        + string #Case 2
3390        impl1.do #module string;
3391        + std
3392        vector.do
3393        list.do
3394        + array #Case 3
3395        array1.do #module std/array;
3396        array2.do #module std/array;
3397        sequence.do #Case 4, module std/sequence;
3398        test.do #Case 5
3399\end{lstlisting}
3400
3401
3402\begin{itemize}
3403\item
3404Case 1: Each individual file implements a module
3405\item
3406Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3407\item
3408Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module
3409\item
3410Case 4: One file to express one aggregation
3411\item
3412Case 5: The file does not belong to any module; It is used for testing purpose
3413\end{itemize}
3414
3415The example only uses source code, ".do" files, to show the module file organization.
3416Other module packaging formats, like binary, must also follow the same rules.
3417
3418
3419\subsubsection{Module File Format}
3420
3421\CFA supports different types of module file formats.
3422
3423\begin{itemize}
3424\item
3425Pure source code format: The files should be organized following the previous section's definition.
3426\item
3427IR format (TBD): The \CFA compiler IR format, similar to the source code format
3428\item
3429Binary format, including ".a" static library or ".so" dynamic linkage library
3430\begin{itemize}
3431\item
3432The file's name must match the right level's module name defined in the previous section
3433\item
3434E.g. "util.so" includes all modules for the package util.
3435\item
3436E.g. "string.so" under the package directory to include files belonging to "module string;"
3437\end{itemize}
3438\item
3439Archive format
3440\begin{itemize}
3441\item
3442The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3443\item
3444E.g. "util.dar" is the whole package for util package including the package direction file
3445\end{itemize}
3446\item
3447Hybrid format
3448\begin{itemize}
3449\item
3450A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3451\item
3452The only limitation is that the names of the files must match the module location names defined in previous section
3453\end{itemize}
3454\end{itemize}
3455
3456
3457\subsection{Package and Module Locating}
3458
3459The 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.
3460If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries.
3461
3462When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order:
3463
3464\begin{enumerate}
3465\item
3466This source file's directory tree, which is typically the project's src directory
3467\item
3468All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory
3469\item
3470The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable
3471\item
3472The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory
3473\item
3474If 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
3475\end{enumerate}
3476
3477The module found first in a package will shadow the modules with the same name in the later packages in the search sequence.
3478
3479
3480\subsubsection{Dependent Package}
3481
3482Dependent packages are those packages containing modules that the current project's source code will import from.
3483Dependent packages are defined implicitly or explicitly in one \CFA project.
3484All of the packages under the current project's pkg directory are implicitly dependent packages.
3485For others, the dependent packages must be defined in the project's Do.prj file.
3486
3487
3488\subsubsection{Package and Module Locating Example}
3489
3490\begin{lstlisting}
3491# A project's source code tree
3492
3493--------------------------------------
3494
3495+ testProject
3496        Do.prj
3497        + src
3498        main.do
3499        + pkg
3500        + security-1.1
3501        Do.prj
3502        security.do #module security
3503
3504--------------------------------------
3505
3506# Do.prj
3507
3508--------------------------------------
3509
3510[dependences]
3511std
3512util = "0.2"
3513
3514--------------------------------------
3515
3516# main.do
3517
3518---------------------------------------
3519
3520import security;
3521import std/vector;
3522import container;
3523
3524----------------------------------------
3525\end{lstlisting}
3526
3527
3528\begin{lstlisting}
3529# pkg directory's source code tree
3530
3531-----------------------------------------
3532
3533+ pkg
3534        + std-1.0
3535        Do.prj
3536        vector.do #module std/vector;
3537        queue.do #module std/queue;
3538        + std-1.1
3539        Do.prj
3540        vector.do #module std/vector;
3541        queue.do #module std/queue;
3542        list.do #module std/list;
3543        + util-0.1
3544        Do.prj
3545        container.do #module container;
3546        + security-1.0
3547        security.do #module security;
3548------------------------------------------
3549\end{lstlisting}
3550
3551
3552During the compiling of main.do file import security;
3553The security module appears in both the local security-1.1 package, and the global security-1.0 package.
3554According to the locating sequence, the local security module in security-1.1 will be used.
3555And because the security-1.1 package is under local's pkg directory.
3556No dependence description is required in the project Do.prj file.
3557
3558import std/vector;
3559
3560The 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.
3561
3562import container;
3563
3564The 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.
3565The builder tool then will try to retrieve it from the web and store it in the global pkg directory.
3566After that, the container module from the newly downloaded package will be used in the compilation.
3567\end{comment}
3568
3569
3570\section{Comparison with Other Languages}
3571
3572\CFA is one of many languages that attempts to improve upon C.
3573In developing \CFA, many other languages were consulted for ideas, constructs, and syntax.
3574Therefore, it is important to show how these languages each compare with Do.
3575In this section, \CFA is compared with what the writers of this document consider to be the closest competitors of Do: \CC, Go, Rust, and D.
3576
3577
3578\subsection{Comparing Key Features of \CFA}
3579
3580
3581\subsubsection{Constructors and Destructors}
3582
3583\lstset{basicstyle=\sf\relsize{-2}}
3584
3585\begin{flushleft}
3586\begin{tabular}{@{}l|l|l|l@{}}
3587\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3588\hline
3589\begin{lstlisting}
3590struct Line {
3591        float length;
3592}
3593// default constructor
3594void ?{}( Line * l ) {
3595        sout | "default" | endl;
3596        l.length = 0.0;
3597}
3598
3599
3600// constructor with length
3601void ?{}( Line * l, float length ) {
3602        sout | "length" | length | endl;
3603
3604        l.length = length;
3605}
3606
3607// destructor
3608void ^?(Line &l) {
3609        sout | "destroyed" | endl;
3610        l.length = 0.0;
3611}
3612
3613// usage
3614Line line1;
3615Line line2{ 3.4 };
3616\end{lstlisting}
3617&
3618\begin{lstlisting}[language=C++]
3619class Line {
3620        float length;
3621
3622        // default constructor
3623        Line() {
3624                cout << "default" << endl;
3625                length = 0.0;
3626        }
3627
3628
3629        // constructor with length
3630        Line( float l ) {
3631                cout << "length " << length
3632                         << endl;
3633                length = l;
3634        }
3635
3636        // destructor
3637        ~Line() {
3638                cout << "destroyed" << endl;
3639                length = 0.0;
3640        }
3641}
3642// usage
3643Line line1;
3644Line line2( 3.4 );
3645\end{lstlisting}
3646&
3647\begin{lstlisting}[language=Golang]
3648type Line struct {
3649        length float32
3650}
3651// default constructor
3652func makeLine() Line {
3653        fmt.PrintLn( "default" )
3654        return Line{0.0}
3655}
3656
3657
3658// constructor with length
3659func makeLine( length float32 ) Line {
3660        fmt.Printf( "length %v", length )
3661
3662        return Line{length}
3663}
3664
3665// no destructor
3666
3667
3668
3669
3670
3671// usage
3672line1 := makeLine()
3673line2 := makeLine( 3.4 )
3674\end{lstlisting}
3675&
3676\begin{lstlisting}
3677struct Line {
3678        length: f32
3679}
3680// default constructor
3681impl Default for Line {
3682        fn default () -> Line {
3683                println!( "default" );
3684                Line{ length: 0.0 }
3685        }
3686}
3687// constructor with length
3688impl Line {
3689        fn make( len: f32 ) -> Line {
3690                println!( "length: {}", len );
3691                Line{ length: len }
3692        }
3693}
3694// destructor
3695impl Drop for Line {
3696        fn drop( &mut self ) {
3697                self.length = 0.0
3698        }
3699}
3700// usage
3701let line1:Line = Default::default();
3702Line line2( 3.4 );
3703\end{lstlisting}
3704\end{tabular}
3705\end{flushleft}
3706
3707
3708\subsubsection{Operator Overloading}
3709
3710\begin{flushleft}
3711\begin{tabular}{@{}l|l|l|l@{}}
3712\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3713\hline
3714\begin{lstlisting}
3715struct Cpx {
3716        double re, im;
3717};
3718// overload addition operator
3719Cpx ?+?( Cpx l, const Cpx r ) {
3720        return (Cpx){l.re+l.im, l.im+r.im};
3721}
3722Cpx a, b, c;
3723c = a + b;
3724\end{lstlisting}
3725&
3726\begin{lstlisting}
3727struct Cpx {
3728        double re, im;
3729};
3730// overload addition operator
3731Cpx operator+( Cpx l, const Cpx r ) {
3732        return (Cpx){l.re+l.im, l.im+r.im};
3733}
3734Cpx a, b, c;
3735c = a + b;
3736\end{lstlisting}
3737&
3738\begin{lstlisting}
3739// no operator overloading
3740
3741
3742
3743
3744
3745
3746
3747\end{lstlisting}
3748&
3749\begin{lstlisting}
3750struct Cpx {
3751        re: f32,
3752        im: f32
3753}
3754// overload addition operator
3755impl Add for Cpx {
3756        type Output = Cpx
3757        fn add(self, r: Cpx) -> Cpx {
3758                let mut res = Cpx{re: 0.0, im: 0.0};
3759                res.re = self.re + r.re;
3760                res.im = self.im + r.im;
3761                return res
3762        }
3763}
3764let (a, b, mut c) = ...;
3765c = a + b
3766\end{lstlisting}
3767\end{tabular}
3768\end{flushleft}
3769
3770
3771\subsubsection{Calling C Functions}
3772
3773\begin{flushleft}
3774\begin{tabular}{@{}l|l|l@{}}
3775\multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}   \\
3776\hline
3777\begin{lstlisting}
3778extern "C" {
3779#include <sys/types.h>
3780#include <sys/stat.h>
3781#include <unistd.h>
3782}
3783size_t fileSize( const char *path ) {
3784        stat s;
3785        stat(path, &s);
3786        return s.st_size;
3787}
3788\end{lstlisting}
3789&
3790\begin{lstlisting}
3791/*
3792#cgo
3793#include <sys/types.h>
3794#include <sys/stat.h>
3795#include <unistd.h>
3796*/
3797import "C"
3798import "unsafe"
3799
3800func fileSize(path string) C.size_t {
3801        var buf C.struct_stat
3802        c_string := C.CString(path)
3803        C.stat(p, &buf)
3804        C.free(unsafe.Pointer(c_string))
3805        return buf._st_size
3806}
3807\end{lstlisting}
3808&
3809\begin{lstlisting}
3810use libc::{c_int, size_t};
3811
3812// The following declarations are
3813// translated from sys/stat.h
3814#[repr(C)]
3815struct stat_t {
3816        ...
3817        st_size: size_t,
3818        ...
3819}
3820
3821#[link(name = "libc")]
3822extern {
3823        fn stat(path: *const u8,
3824        buf: *mut stat_t) -> c_int;
3825}
3826
3827fn fileSize(path: *const u8) -> size_t
3828{
3829        unsafe {
3830        let mut buf: stat_t = uninit();
3831        stat(path, &mut buf);
3832        buf.st_size
3833        }
3834}
3835\end{lstlisting}
3836\end{tabular}
3837\end{flushleft}
3838
3839
3840\subsubsection{Generic Functions}
3841
3842\begin{flushleft}
3843\begin{tabular}{@{}l|l|l|l@{}}
3844\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3845\hline
3846\begin{lstlisting}
3847generic(type T, type N |
3848        { int ?<?(N, N); })
3849T *maximize(N (*f)(const T&),
3850        int n, T *a) {
3851        T *bestX = NULL;
3852        N bestN;
3853        for (int i = 0; i < n; i++) {
3854        N curN = f(a[i]);
3855        if (bestX == NULL ||
3856        curN > bestN) {
3857        bestX = &a[i]; bestN = curN;
3858        }
3859        }
3860        return bestX;
3861}
3862
3863string *longest(int n, string *p)
3864{
3865        return maximize(length, n, p);
3866}
3867\end{lstlisting}
3868&
3869\begin{lstlisting}
3870template<typename T, typename F>
3871T *maximize(const F &f,
3872        int n, T *a) {
3873        typedef decltype(f(a[0])) N;
3874        T *bestX = NULL;
3875        N bestN;
3876        for (int i = 0; i < n; i++) {
3877        N curN = f(a[i]);
3878        if (bestX == NULL || curN > bestN)
3879        {
3880        bestX = &a[i]; bestN = curN;
3881        }
3882        }
3883        return bestX;
3884}
3885
3886string *longest(int n, string *p) {
3887        return maximize(
3888        [](const string &s) {
3889        return s.length();
3890        }, n, p);
3891}
3892\end{lstlisting}
3893&
3894\begin{lstlisting}
3895// Go does not support generics!
3896func maximize(
3897        gt func(interface{}, interface{}) bool,
3898        f func(interface{}) interface{},
3899        a []interface{}) interface{} {
3900        var bestX interface{} = nil
3901        var bestN interface{} = nil
3902        for _, x := range a {
3903        curN := f(x)
3904        if bestX == nil || gt(curN, bestN)
3905        {
3906        bestN = curN
3907        bestX = x
3908        }
3909        }
3910        return bestX
3911}
3912
3913func longest(
3914        a []interface{}) interface{} {
3915        return maximize(
3916        func(a, b interface{}) bool {
3917        return a.(int) > b.(int) },
3918        func(s interface{}) interface{} {
3919        return len(s.(string)) },
3920        a).(string)
3921}
3922\end{lstlisting}
3923&
3924\begin{lstlisting}
3925use std::cmp::Ordering;
3926
3927fn maximize<N: Ord + Copy, T, F:
3928Fn(&T) -> N>(f: F, a: &Vec<T>) ->
3929Option<&T> {
3930        let mut best_x: Option<&T> = None;
3931        let mut best_n: Option<N> = None;
3932        for x in a {
3933        let n = f(x);
3934        if (match best_n { None => true,
3935        Some(bn) =>
3936        n.cmp(&bn) == Ordering::Greater })
3937        {
3938        best_x = Some(x);
3939        best_n = Some(n);
3940        }
3941        }
3942        return best_x
3943}
3944
3945fn longest(a: &Vec<String>) ->
3946        Option<&String> {
3947        return
3948        maximize(|x: &String| x.len(), a)
3949}
3950\end{lstlisting}
3951\end{tabular}
3952\end{flushleft}
3953
3954
3955\subsubsection{Modules/Packages}
3956
3957\begin{lstlisting}
3958\CFA
3959\CC
3960
3961
3962module example/M;
3963
3964export int inc(int val) {
3965        return val + 1;
3966}
3967
3968
3969
3970
3971--------------------------------------
3972//Use the module in another file
3973import example/M;
3974int main() {
3975        print(M.inc(100));
3976        return 0;
3977}
3978// Using \CC17 module proposal
3979
3980module example.M;
3981
3982export {
3983        int inc(int val);
3984}
3985
3986int inc(inv val) {
3987        return val + 1;
3988}
3989--------------------------------------
3990// Use the module in another file
3991import example.M;
3992int main() {
3993        cout << inc(100) << endl;
3994        return 0;
3995}
3996
3997Go
3998Rust
3999package example/M;
4000
4001func Inc(val int32) int32 {
4002        // Capitalization indicates exported
4003        return val + 100
4004}
4005
4006
4007--------------------------------------
4008//Use the package in another file
4009package main
4010import .fmt.
4011import "example/M"
4012
4013func main() int32 {
4014        fmt.Printf(.%v., M.Inc(100))
4015}
4016pub mod example {
4017        pub mod M {
4018        pub inc(val i32) -> i32 {
4019        return val + 100;
4020        }
4021        }
4022}
4023
4024--------------------------------------
4025//Use the module in another file
4026use example::M;
4027
4028
4029
4030fn main() {
4031        println!(.{}., M::inc(100));
4032}
4033\end{lstlisting}
4034
4035\subsubsection{Parallel Tasks}
4036
4037\begin{flushleft}
4038\begin{tabular}{@{}l|l|l|l@{}}
4039\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4040\hline
4041\begin{lstlisting}
4042task Nonzero {
4043        int *data;
4044        int start;
4045        int end;
4046        int* res;
4047};
4048
4049void ?{}(Nonzero &a, int d[], int s,
4050        int e, int* subres) {
4051        // constructor
4052        a.data = d;
4053        a.start = s;
4054        a.end = e;
4055        a.res = subres;
4056}
4057
4058// implicitly spawn thread here
4059void ?()(NonzeroCounter &a) {
4060        int i;
4061        int nonzero = 0;
4062        for (i=start; c<end; ++i) {
4063        if(a.data[i]!=0){ nonzero++;}
4064        }
4065        *a.res = nonzero;
4066}
4067
4068int main() {
4069        int sz = ...
4070        int data[sz] = ...;
4071        int r1 = 0, r2=0;
4072        int res;
4073        { // create a scope for Nonzero
4074        Nonzero n1{data, 0, sz/2, &n1};
4075        Nonzero n2{data, sz/2, sz, &n2};
4076        n1();//spawn
4077        n2();//spawn
4078        }
4079        res = r1+r2;
4080        return res;
4081}
4082\end{lstlisting}
4083&
4084\begin{lstlisting}
4085#include <thread>
4086#include <mutex>
4087
4088std::mutex m;
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101void task(const vector<int>&v,
4102        int* res, size_t s,
4103        size_t e) {
4104        int non_zero = 0;
4105        for(size_t i = s; i < e; ++i){
4106        if(v[i]!=0) { non_zero++;}
4107        }
4108        std::unique_lock<mutex> lck {m};
4109        *res += non_zero;
4110}
4111
4112int main() {
4113        vector<int> data = ...; //data
4114        int res = 0;
4115        std::thread t1 {task, ref(data),
4116        &res, 0,
4117        data.size()/2};
4118        std::thread t2 {task, ref(data),
4119        &res, data.size()/2,
4120        data.size()};
4121        t1.join();
4122        t2.join();
4123        return res;
4124}
4125\end{lstlisting}
4126&
4127\begin{lstlisting}
4128package main
4129
4130import "fmt"
4131
4132func nonzero(data []int, c chan int) {
4133        nz := 0
4134        for _, v:=range data {
4135        if(v!=0) { nz := nz+1 }
4136        }
4137        c <- nz
4138}
4139
4140func main() {
4141        sz := ...
4142        data := make([]int, sz)
4143        ... // data init
4144        go nonzero(data[:len(data)/2], c)
4145        go nonzero(data[len(data)/2:], c)
4146        n1, n2 := <-c, <-c
4147        res := n1 + n2
4148        fmt.Println(res)
4149}
4150\end{lstlisting}
4151&
4152\begin{lstlisting}
4153use std::thread;
4154use std::sync:mpsc::channel;
4155
4156fn main() {
4157        let sz = ...;
4158        let mut data:Vec<i32> =
4159        Vec::with_capacity(sz as usize);
4160        ... //init data
4161        let (tx, rx) = channel();
4162        for i in 0..1 {
4163        let tx = tx.clone();
4164        let data = data.clone()
4165        thread::spawn(move|| {
4166        let mut nz := 0;
4167        let mut s = 0;
4168        let mut e = sz / 2;
4169        if i == 1 {
4170        s = sz/2;
4171        e = data.len();
4172        }
4173        for i in s..(e - 1) {
4174        if data[i] != 0 (
4175        nz = nz + 1
4176        }
4177        }
4178        tx.send(nz).unwrap();
4179        });
4180        }
4181        let res = rx.recv().unwrap() +
4182        rx.recv().unwrap();
4183        println!(.{}., res);
4184}
4185\end{lstlisting}
4186\end{tabular}
4187\end{flushleft}
4188
4189\subsection{Summary of Language Comparison}
4190
4191
4192\subsubsection{\CC}
4193
4194\CC is a general-purpose programming language.
4195It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia)
4196
4197The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do.
4198\CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data.
4199\CFA uses modules instead to perform these same tasks.
4200Classes in \CC also enable inheritance among types.
4201Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility.
4202There 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, Go at Google: Language Design in the Service of Software Engineering , 2012).
4203
4204Overloading 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.
4205References and exceptions in \CFA are heavily based on the same features from \CC.
4206The mechanism for interoperating with C code in \CFA is also borrowed from \CC.
4207
4208Both \CFA and \CC provide generics, and the syntax is quite similar.
4209The 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.
4210This means that a generic function can be defined in a compiled library, and still be used as expected from source.
4211
4212
4213\subsubsection{Go}
4214
4215Go, also commonly referred to as golang, is a programming language developed at Google in 2007 [.].
4216It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type
4217safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia)
4218
4219Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned.
4220Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction.
4221Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse.
4222Both 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.
4223
4224Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks.
4225\CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection.
4226This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead.
4227
4228
4229\subsubsection{Rust}
4230
4231Rust is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research.
4232It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles.
4233
4234The primary focus of Rust is in safety, especially in concurrent programs.
4235To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety.
4236This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead.
4237
4238Aside from those key differences, Rust and \CFA also have several similarities.
4239Both languages support no overhead interoperability with C and have minimal runtimes.
4240Both languages support inheritance and polymorphism through the use of interfaces (traits).
4241
4242
4243\subsubsection{D}
4244
4245The D programming language is an object-oriented, imperative, multi-paradigm system programming
4246language created by Walter Bright of Digital Mars and released in 2001. [.]
4247Though 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 Java, Python, Ruby, C\#, and Eiffel.
4248
4249D and \CFA both start with C and add productivity features.
4250The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces.
4251D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces.
4252Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates.
4253D does not have any built-in concurrency constructs in the
4254language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency.
4255
4256
4257\bibliographystyle{plain}
4258\bibliography{/usr/local/bibliographies/pl.bib}
4259
4260
4261\addcontentsline{toc}{section}{\indexname} % add index name to table of contents
4262\begin{theindex}
4263Italic page numbers give the location of the main entry for the referenced term.
4264Plain page numbers denote uses of the indexed term.
4265Entries for grammar non-terminals are italicized.
4266A typewriter font is used for grammar terminals and program identifiers.
4267\indexspace
4268\input{user.ind}
4269\end{theindex}
4270
4271
4272\end{document}
4273
4274% Local Variables: %
4275% tab-width: 4 %
4276% fill-column: 100 %
4277% compile-command: "make" %
4278% End: %
Note: See TracBrowser for help on using the repository browser.